Spring Security JSP Tag Library
Spring Security Tag Library, Introduction, Features, Project Modules, XML Example, Java Example, Login Logout, Spring Boot, Spring Core, Spring with JPA, Spring with Hibernate, Spring with Struts, Spring MVC, Spring Integration etc.

Spring Security JSP Tag Library
Spring Security provides its own tags for jsp pages. These tags are used to access security information and apply security constraints in JSPs.
The following tags are used to secure view layer of the application.
- Authorize Tag
- Authentication Tag
- Accesscontrollist Tag
- Csrfinput Tag
- CsrfMetaTags Tag
Authorize Tag
This tag is used for authorization purpose. This tag evaluates and check whether the request is authorized or not.
It uses two attributes access and URL to check request authorization. We can pass user's role to evaluate this tag.
The content written inside this tag will display only if the attribute is satisfy. For example.
- <sec:authorize access="hasRole('ADMIN')">
- It will display only is user is admin
- </sec:authorize>
Authentication Tag
This tag is used to access the authentication stored into the security context. It can be used to get current user details if the Authentication is an instance of UserDetails object. For example.
- <sec:authentication property="principal.username">
Accesscontrollist Tag
This tag is used with Spring Security's ACL module. It checks list of required permissions for the specified domains. It executes only if current user has all the permissions. For example.
- <sec:accesscontrollist hasPermission="1,2" domainObject="${someObject}">
- If user has all the permissions represented by the values "1" or "2" on the given object.
- </sec:accesscontrollist>
CsrfInput Tag
This tag is used to create CSRF tokens for the HTML form. To use it make sure CSRF protection is enabled. We should place this tag inside the <form></form> tag to create CSRF token. For example.
- <form method="post" action="/some/action">
- <sec:csrfInput />
- Name:<br />
- <input type="text" name="username" />
- ...
- </form>
CsrfMetaTags Tag
It inserts meta tag that contains CSRF token, form field, header name and CSRF token value. These values are useful to set CSRF token within JavaScript in the application.
This tag should place inside the HTML <head> tag.
Spring Security Taglib JAR
To implement any of these tags, we must have spring security taglib jar in our application. It can also be added using following maven dependecy.
- <dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-taglibs</artifactId>
- <version>5.0.4.RELEASE</version>
- </dependency>
Spring Security Taglib Declaration
In JSP page, we can use taglib by using the following declaration.
- <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
Now, lets see an example to implement these tags in spring security maven project.
We are using STS (Spring Tool Suite) to create the project. See the example.
Create Project
Click on finish button and it will create a maven project that looks like this:
Spring Security Configuration
To configure Spring Security in the Spring MVC application, put the following four files inside the com.javatpoint folder.
AppConfig.java
- package com.tpoint;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.EnableWebMvc;
- import org.springframework.web.servlet.view.InternalResourceViewResolver;
- import org.springframework.web.servlet.view.JstlView;
- @EnableWebMvc
- @Configuration
- @ComponentScan({ "com.javatpoint.controller.*" })
- public class AppConfig {
- @Bean
- public InternalResourceViewResolver viewResolver() {
- InternalResourceViewResolver viewResolver
- = new InternalResourceViewResolver();
- viewResolver.setViewClass(JstlView.class);
- viewResolver.setPrefix("/WEB-INF/views/");
- viewResolver.setSuffix(".jsp");
- return viewResolver;
- }
- }
The AppConfig is used to set view location suffix of the view files.
// MvcWebApplicationInitializer.java
- package com.tpoint;
- import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
- public class MvcWebApplicationInitializer extends
- AbstractAnnotationConfigDispatcherServletInitializer {
- @Override
- protected Class<?>[] getRootConfigClasses() {
- return new Class[] { WebSecurityConfig.class };
- }
- @Override
- protected Class<?>[] getServletConfigClasses() {
- // TODO Auto-generated method stub
- return null;
- }
- @Override
- protected String[] getServletMappings() {
- return new String[] { "/" };
- }
- }
This class is used to initialize servlet dispatcher.
// SecurityWebApplicationInitializer.java
- package com.tpoint;
- import org.springframework.security.web.context.*;
- public class SecurityWebApplicationInitializer
- extends AbstractSecurityWebApplicationInitializer {
- }
Create one more class that is used to create user and apply authentication and authorization on the user accessibility.
// WebSecurityConfig.java
- package com.tpoint;
- import org.springframework.context.annotation.*;
- import org.springframework.security.config.annotation.web.builders.HttpSecurity;
- import org.springframework.security.config.annotation.web.configuration.*;
- import org.springframework.security.core.userdetails.*;
- import org.springframework.security.core.userdetails.User.UserBuilder;
- import org.springframework.security.provisioning.InMemoryUserDetailsManager;
- import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
- @EnableWebSecurity
- @ComponentScan("com.javatpoint")
- public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
- @Bean
- public UserDetailsService userDetailsService() {
- // ensure the passwords are encoded properly
- UserBuilder users = User.withDefaultPasswordEncoder();
- InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
- manager.createUser(users.username("mohan").password("1mohan23").roles("USER").build());
- manager.createUser(users.username("admin").password("admin123").roles("ADMIN").build());
- return manager;
- }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().
- antMatchers("/index","/").permitAll()
- .antMatchers("/admin","/user").authenticated()
- .and()
- .formLogin()
- .and()
- .logout()
- .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
- }
- }
Controller
Now, create a controller to handle request and respond back.
// HomeController.java
- package com.tpoint.controller;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- @Controller
- public class HomeController {
- @RequestMapping(value="/", method=RequestMethod.GET)
- public String index() {
- return "index";
- }
- @RequestMapping(value="/user", method=RequestMethod.GET)
- public String user() {
- return "admin";
- }
- @RequestMapping(value="/admin", method=RequestMethod.GET)
- public String admin() {
- return "admin";
- }
- }
View
Create view (jsp) files to show the output to the user. We have created three JSP files, see the below.
// index.jsp
- <html>
- <head>
- <title>Home Page</title>
- </head>
- <body>
- <a href="user">User</a> <a href="admin">Admin</a> <br> <br>
- Welcome to hpnmaratt!
- </body>
- </html>
// user.jsp
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Home Page</title>
- </head>
- <body>
- Welcome to user page!
- </body>
- </html>
// admin.jsp
In the admin page, we have used authorize tag to that evaluates only when the given role is satisfied.
- <%@ taglib uri="http://www.springframework.org/security/tags" prefix="security" %><html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Home Page</title>
- </head>
- <body>
- Welcome to admin page!
- <a href="logout">logout</a> <br><br>
- <security:authorize access="hasRole('ADMIN')">
- Hello ADMIN
- </security:authorize>
- <security:csrfInput/>
- </body>
- </html>
Project Dependencies
Our project contains the following dependencies that are required to build application.
// pom.xml
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.javatpoint</groupId>
- <artifactId>springtaglibrary</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>war</packaging>
- <properties>
- <maven.compiler.target>1.8</maven.compiler.target>
- <maven.compiler.source>1.8</maven.compiler.source>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>5.0.2.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-web</artifactId>
- <version>5.0.0.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-core</artifactId>
- <version>5.0.4.RELEASE</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs -->
- <dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-taglibs</artifactId>
- <version>5.0.4.RELEASE</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
- <dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-config</artifactId>
- <version>5.0.4.RELEASE</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- <version>3.1.0</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jstl</artifactId>
- <version>1.2</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/org.springframework/spring-framework-bom -->
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-war-plugin</artifactId>
- <version>2.6</version>
- <configuration>
- <failOnMissingWebXml>false</failOnMissingWebXml>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
After adding all these files, our project looks like this:
Run the Application
Right click on the project and select run on server. It shows the following output to the browser.
Click on the User and Login by providing credentials that are set in AppSecurityConfig file.
After successful login, it shows the admin page that looks like below. Here, notice that the content written inside the authorize tag is not displayed because logged in user has role USER.
Logout and now login as an admin by providing admin credentials.
After logged in as admin, see this time the authorize tag evaluates and it shows the following output.