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 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.

  1. <sec:authorize access="hasRole('ADMIN')">  
  2. It will display only is user is admin  
  3. </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.

  1. <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.

  1. <sec:accesscontrollist hasPermission="1,2" domainObject="${someObject}">  
  2.  If user has all the permissions represented by the values "1" or "2" on the given object.  
  3. </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.

  1. <form method="post" action="/some/action">  
  2.                 <sec:csrfInput />  
  3.                 Name:<br />  
  4.                 <input type="text" name="username" />  
  5.                 ...  
  6.         </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.

  1. <dependency>  
  2.     <groupId>org.springframework.security</groupId>  
  3.     <artifactId>spring-security-taglibs</artifactId>  
  4.     <version>5.0.4.RELEASE</version>  
  5. </dependency>  

Spring Security Taglib Declaration

In JSP page, we can use taglib by using the following declaration.

  1. <%@ 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

  1. package com.tpoint;  
  2. import org.springframework.context.annotation.Bean;    
  3. import org.springframework.context.annotation.ComponentScan;    
  4. import org.springframework.context.annotation.Configuration;    
  5. import org.springframework.web.servlet.config.annotation.EnableWebMvc;    
  6. import org.springframework.web.servlet.view.InternalResourceViewResolver;    
  7. import org.springframework.web.servlet.view.JstlView;    
  8.     
  9. @EnableWebMvc    
  10. @Configuration    
  11. @ComponentScan({ "com.javatpoint.controller.*" })    
  12. public class AppConfig {    
  13.     @Bean    
  14.     public InternalResourceViewResolver viewResolver() {    
  15.         InternalResourceViewResolver viewResolver    
  16.                           = new InternalResourceViewResolver();    
  17.         viewResolver.setViewClass(JstlView.class);    
  18.         viewResolver.setPrefix("/WEB-INF/views/");    
  19.         viewResolver.setSuffix(".jsp");    
  20.         return viewResolver;    
  21.     }    

The AppConfig is used to set view location suffix of the view files.

// MvcWebApplicationInitializer.java

  1. package com.tpoint;  
  2.   
  3. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;    
  4. public class MvcWebApplicationInitializer extends    
  5.         AbstractAnnotationConfigDispatcherServletInitializer {    
  6.     @Override    
  7.     protected Class<?>[] getRootConfigClasses() {    
  8.         return new Class[] { WebSecurityConfig.class };    
  9.     }    
  10.     @Override    
  11.     protected Class<?>[] getServletConfigClasses() {    
  12.         // TODO Auto-generated method stub    
  13.         return null;    
  14.     }    
  15.     @Override    
  16.     protected String[] getServletMappings() {    
  17.         return new String[] { "/" };    
  18.     }    
  19. }  

This class is used to initialize servlet dispatcher.

// SecurityWebApplicationInitializer.java

  1. package com.tpoint;  
  2. import org.springframework.security.web.context.*;    
  3. public class SecurityWebApplicationInitializer    
  4.     extends AbstractSecurityWebApplicationInitializer {    
  5.     
  6. }    

Create one more class that is used to create user and apply authentication and authorization on the user accessibility.

// WebSecurityConfig.java

  1. package com.tpoint;  
  2.   
  3. import org.springframework.context.annotation.*;  
  4. import org.springframework.security.config.annotation.web.builders.HttpSecurity;    
  5. import org.springframework.security.config.annotation.web.configuration.*;    
  6. import org.springframework.security.core.userdetails.*;  
  7. import org.springframework.security.core.userdetails.User.UserBuilder;    
  8. import org.springframework.security.provisioning.InMemoryUserDetailsManager;  
  9. import org.springframework.security.web.util.matcher.AntPathRequestMatcher;  
  10. @EnableWebSecurity    
  11. @ComponentScan("com.javatpoint")    
  12. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {    
  13.     
  14. @Bean    
  15. public UserDetailsService userDetailsService() {  
  16.     // ensure the passwords are encoded properly  
  17.      UserBuilder users = User.withDefaultPasswordEncoder();  
  18.      InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();  
  19.      manager.createUser(users.username("mohan").password("1mohan23").roles("USER").build());  
  20.      manager.createUser(users.username("admin").password("admin123").roles("ADMIN").build());  
  21.      return manager;  
  22.     }   
  23.     
  24. @Override    
  25. protected void configure(HttpSecurity http) throws Exception {    
  26.         
  27.       http.authorizeRequests().  
  28.       antMatchers("/index","/").permitAll()  
  29.       .antMatchers("/admin","/user").authenticated()  
  30.       .and()  
  31.       .formLogin()  
  32.       .and()  
  33.       .logout()  
  34.       .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));  
  35.           
  36. }    
  37. }  

Controller

Now, create a controller to handle request and respond back.

// HomeController.java

  1. package com.tpoint.controller;  
  2. import org.springframework.stereotype.Controller;    
  3. import org.springframework.web.bind.annotation.RequestMapping;    
  4. import org.springframework.web.bind.annotation.RequestMethod;  
  5. @Controller    
  6. public class HomeController {    
  7.     @RequestMapping(value="/"method=RequestMethod.GET)    
  8.     public String index() {    
  9.         return "index";    
  10.     }    
  11.     @RequestMapping(value="/user"method=RequestMethod.GET)    
  12.     public String user() {    
  13.        return "admin";  
  14.     }    
  15.     @RequestMapping(value="/admin"method=RequestMethod.GET)    
  16.     public String admin() {    
  17.             
  18.         return "admin";    
  19.     }  
  20.    

View

Create view (jsp) files to show the output to the user. We have created three JSP files, see the below.

// index.jsp

  1. <html>    
  2. <head>    
  3. <title>Home Page</title>    
  4. </head>    
  5. <body>    
  6. <a href="user">User</a> <a href="admin">Admin</a> <br> <br>  
  7. Welcome to hpnmaratt!    
  8. </body>    
  9. </html>   

// user.jsp

  1. <html>    
  2. <head>    
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
  4. <title>Home Page</title>    
  5. </head>    
  6. <body>    
  7. Welcome to user page!    
  8. </body>    
  9. </html>   

// admin.jsp

In the admin page, we have used authorize tag to that evaluates only when the given role is satisfied.

  1. <%@ taglib uri="http://www.springframework.org/security/tags" prefix="security" %><html>    
  2. <head>    
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">   
  4. <title>Home Page</title>    
  5. </head>    
  6. <body>    
  7. Welcome to admin page!  
  8. <a href="logout">logout</a> <br><br>  
  9. <security:authorize access="hasRole('ADMIN')">  
  10. Hello ADMIN  
  11. </security:authorize>  
  12. <security:csrfInput/>  
  13. </body>    
  14. </html>   

Project Dependencies

Our project contains the following dependencies that are required to build application.

// pom.xml

  1. <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">  
  2.   <modelVersion>4.0.0</modelVersion>  
  3.   <groupId>com.javatpoint</groupId>  
  4.   <artifactId>springtaglibrary</artifactId>  
  5.   <version>0.0.1-SNAPSHOT</version>  
  6.   <packaging>war</packaging>  
  7.   <properties>    
  8.     <maven.compiler.target>1.8</maven.compiler.target>    
  9.     <maven.compiler.source>1.8</maven.compiler.source>    
  10. </properties>    
  11. <dependencies>    
  12.   <dependency>    
  13.             <groupId>org.springframework</groupId>    
  14.             <artifactId>spring-webmvc</artifactId>    
  15.             <version>5.0.2.RELEASE</version>    
  16.         </dependency>    
  17.         <dependency>    
  18.         <groupId>org.springframework.security</groupId>    
  19.         <artifactId>spring-security-web</artifactId>    
  20.         <version>5.0.0.RELEASE</version>    
  21.     </dependency>    
  22. <dependency>  
  23.     <groupId>org.springframework.security</groupId>  
  24.     <artifactId>spring-security-core</artifactId>  
  25.     <version>5.0.4.RELEASE</version>  
  26. </dependency>  
  27. <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs -->  
  28. <dependency>  
  29.     <groupId>org.springframework.security</groupId>  
  30.     <artifactId>spring-security-taglibs</artifactId>  
  31.     <version>5.0.4.RELEASE</version>  
  32. </dependency>  
  33.     <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->  
  34. <dependency>  
  35.     <groupId>org.springframework.security</groupId>  
  36.     <artifactId>spring-security-config</artifactId>  
  37.     <version>5.0.4.RELEASE</version>  
  38. </dependency>  
  39.         <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->    
  40. <dependency>    
  41.     <groupId>javax.servlet</groupId>    
  42.     <artifactId>javax.servlet-api</artifactId>    
  43.     <version>3.1.0</version>    
  44.     <scope>provided</scope>    
  45. </dependency>    
  46. <dependency>    
  47.     <groupId>javax.servlet</groupId>    
  48.     <artifactId>jstl</artifactId>    
  49.     <version>1.2</version>    
  50. </dependency>    
  51. <!-- https://mvnrepository.com/artifact/org.springframework/spring-framework-bom -->  
  52. </dependencies>    
  53.   <build>    
  54.     <plugins>    
  55.         <plugin>    
  56.             <groupId>org.apache.maven.plugins</groupId>    
  57.             <artifactId>maven-war-plugin</artifactId>    
  58.             <version>2.6</version>    
  59.             <configuration>    
  60.                 <failOnMissingWebXml>false</failOnMissingWebXml>    
  61.             </configuration>    
  62.         </plugin>    
  63.     </plugins>    
  64. </build>    
  65. </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.