Spring Security provides a powerful JSP Tag Library that allows developers to manage authentication and authorization directly in JSP files. This enables role-based access control, displaying user information, and protecting forms without writing Java code in the JSP.
Prerequisites
- Java 11 or later
- Maven or Gradle
- Spring Boot with Spring Security (Latest version: 6.x)
- JSP and Servlet API
Step-by-Step Implementation
Step 1: Add Spring Security Dependencies
Add the following dependencies to your pom.xml:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>6.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>6.2.0</version>
</dependency>
The spring-security-taglibs dependency provides the JSP tag library required for securing pages.
Step 2: Configure Spring Security
Java Config (Recommended for Spring Security 6+):
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(form -> form
.loginPage("/login")
.defaultSuccessUrl("/home")
)
.logout(logout -> logout
.logoutSuccessUrl("/login?logout")
);
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails admin = User.withUsername("admin")
.password("{noop}admin123") // For demo only, use BCryptPasswordEncoder in production
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(admin);
}
}
Legacy XML Configuration (Optional):
<http auto-config="true">
<intercept-url pattern="/admin/**" access="hasRole('ADMIN')"/>
<form-login login-page="/login"/>
<logout logout-url="/logout"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="{noop}admin123" authorities="ROLE_ADMIN"/>
</user-service>
</authentication-provider>
</authentication-manager>
Step 3: Use Spring Security Tags in JSP
Add the tag library declaration at the top of your JSP:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
1. Role-Based Access (authorize)
<sec:authorize access="hasRole('ADMIN')">
<p>Admin-only content!</p>
<a href="/admin/dashboard">Admin Dashboard</a>
</sec:authorize>
2. Display User Info (authentication)
Welcome, <sec:authentication property="name"/>!
Your roles: <sec:authentication property="authorities"/>
3. CSRF Protection (csrfInput)
<form action="/update" method="post">
<sec:csrfInput />
<input type="text" name="data"/>
<button type="submit">Submit</button>
</form>
4. Logout Button (logout)
<sec:authorize access="isAuthenticated()">
<form action="/https/www.geeksforgeeks.org/logout" method="post">
<sec:csrfInput />
<button type="submit">Logout</button>
</form>
</sec:authorize>
Other Useful JSP Security Tags
- sec:authorize: Controls access to parts of a page based on roles or authentication
- sec:authentication: Displays information about the current user (username, roles)
- sec:csrfInput: Generates a hidden input field with the CSRF token for forms
- sec:csrfMetaTags: Adds CSRF tokens as meta tags for JavaScript usage
- sec:http: Generates HTTP method input fields for forms
- sec:logout: Creates a logout link/button
- sec:accessDenied: Displays content when a user is not authorized to access a page
Complete Example: Admin Dashboard
admin.jsp:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<!DOCTYPE html>
<html>
<head>
<title>Admin Panel</title>
</head>
<body>
<sec:authorize access="hasRole('ADMIN')">
<h1>Admin Dashboard</h1>
<p>Logged in as: <sec:authentication property="name"/></p>
<form action="/logout" method="post">
<sec:csrfInput />
<button type="submit">Logout</button>
</form>
</sec:authorize>
</body>
</html>
- Only users with the ADMIN role can view the dashboard content.
- The page displays the logged-in username and provides a secure logout button.
- CSRF tokens are automatically included in forms using <sec:csrfInput />.
Benefits of Using Spring Security JSP Tags
- Secure pages without writing Java code in JSP.
- Role-based content rendering is straightforward.
- Simplifies CSRF protection in forms.
- Enables easy display of user information (username, roles).
- Integrates seamlessly with Spring Security authentication and authorization.