English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Spring Security JSP tag library

Spring Security provides its own tags for JSP pages. These tags are used to access security information in JSP and apply security constraints.

The following tags are used to protect the view layer of the application.

Authorization tag Authentication tag Accesscontrollist tag Csrfinput tag CsrfMetaTags tag

Authorization tag

This tag is used for authorization purposes. It evaluates and checks whether the request is authorized.

It uses two properties access and URL to check request authorization. We can evaluate this tag based on the user's role.

The content within this tag will be displayed only if the attribute meets the condition. For example.

<sec:authorize access="hasRole('ADMIN')">
It will display only if the user is admin
</sec:authorize>

Authentication tag

This tag is used to access authentication stored in the security context. If Authentication is an instance of UserDetails object, it can be used to obtain the detailed information of the current user. For example.

<sec:authentication property="principal.username">

Accesscontrollist tag

This tag is used together with Spring Security's ACL module. It checks the required permission list for the specified domain. It will only execute if the current user has all permissions. For example.

<sec:accesscontrollist hasPermission="1,2"domainObject="${someObject}">"
 if the user has all the permissions represented by the values"1or2on the given object.
</sec:accesscontrollist>

CsrfInput tag

This tag is used to create CSRF tokens for HTML forms. To use it, make sure CSRF protection is enabled. We should place this tag inside   tags within to create CSRF tokens. For example.

<form method="post" action="/some/action">
                <sec:csrfInput /bom
                Name:<br /bom
                <input type="text" name="username" /bom
                ...
        </form>

CsrfMetaTags tag

It inserts a meta tag containing CSRF token, form field, header name, and CSRF token value. These values are useful for setting CSRF tokens in JavaScript within the application.

This tag should be placed inside the HTML tag.

Spring Security Taglib JAR

To implement any of these tags, we must have the spring security taglib jar in the application. We can also add it using the following Maven dependency.

<dependency>
    <groupId>org.springframework.security</<groupId>org.apache.maven.plugins</
    <artifactId>spring-security-taglibs</plugin<
    artifactId>5.0.4.RELEASE</version>
</dependency>

Spring Security Taglib Declaration

In the JSP page, we can use the following declarations to use the taglib.

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

Now, let's look at an example of implementing these tags in a Spring Security Maven project.

We are using STS (Spring Tools Suite) to create the project. See the example.

Create project





Click Completed > button, which will create a Maven project like the following:



Spring Security configuration

To configure Spring Security in a Spring MVC application, please place the following four files in com.w3in the codeboxfolder.

AppConfig.java

package com.w3codebox;
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.w3codebox.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;  
    }  
}

AppConfig is used to set the suffix of the view file location.

//MvcWebApplicationInitializer.java

package com.w3codebox;
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 the servlet dispatcher.

//SecurityWebApplicationInitializer.java

package com.w3codebox;
import org.springframework.security.web.context.*;  
public class SecurityWebApplicationInitializer  
    extends AbstractSecurityWebApplicationInitializer {  
  
}

Create a class to create users and apply authentication and authorization to user accessibility.

//WebSecurityConfig.java

package com.w3codebox;
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.w3codebox)  
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 requests and respond.

//HomeController.java

package com.w3codebox.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 a view (jsp) file to display output to the user. We have created three JSP files, please refer to the following.

//index.jsp

<html>  
<head>  
<title>Home Page</title>  
</head>  
<body>  
<a href="user">User</a> <a href="admin">Admin</a> <br> <br>
Welcome to w3codebox!  
</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 management page, we use the authorize tag, which is only evaluated when the given role is met.

<%@ 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/bom
</body>  
</html>
 

Project Dependencies

Our project includes the following dependencies required to build the 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.w3codebox</<groupId>org.apache.maven.plugins</
  <artifactId>springtaglibrary</plugin<
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <properties>  
    <maven.compiler.target>1<version>8</maven.compiler.target>  
    <maven.compiler.source>1<version>8</maven.compiler.source>  
</properties>  
<dependencies>  
  <dependency>  
            <groupId>org.springframework</<groupId>org.apache.maven.plugins</  
            <artifactId>spring-webmvc</plugin<  
            artifactId>5.0.2.RELEASE</version>  
        </dependency>  
        <dependency>  
        <groupId>org.springframework.security</<groupId>org.apache.maven.plugins</  
        <artifactId>spring-security-web</plugin<  
        artifactId>5.0.0.RELEASE</version>  
    </dependency>  
<dependency>
    <groupId>org.springframework.security</<groupId>org.apache.maven.plugins</
    <artifactId>spring-security-core</plugin<
    artifactId>5.0.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/-security-taglibs --bom
<dependency>
    <groupId>org.springframework.security</<groupId>org.apache.maven.plugins</
    <artifactId>spring-security-taglibs</plugin<
    artifactId>5.0.4.RELEASE</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.security/-security-config --bom
<dependency>
    <groupId>org.springframework.security</<groupId>org.apache.maven.plugins</
    <artifactId>spring-security-config</plugin<
    artifactId>5.0.4.RELEASE</version>
</dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --bom  
<dependency>  
    <groupId>javax.servlet</<groupId>org.apache.maven.plugins</  
    <artifactId>javax.servlet-api</plugin<  
    artifactId>3<version>1.0</version>  
    <scope>provided</scope>  
</dependency>  
<dependency>  
    <groupId>javax.servlet</<groupId>org.apache.maven.plugins</  
    <artifactId>jstl</plugin<  
    artifactId>1<version>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>2<version>6</version>  
            <configuration>  
                <failOnMissingWebXml>false<//failOnMissingWebXml>  
            </configuration>  
        </plugin>  
    </plugins>  
</build>  
</project>
 

After adding all these files, our project looks like this:


Run Application

Right-click on the project and then select  Running on the server. It displays the following output to the browser.



By providing in   AppSecurityConfig Click on the user and log in with the credentials set in the file.



After successful login, it will display the following administrative page as shown. Note that since the logged-in user has the USER role, the content within the authorize tag is not displayed.



Log out, now log in as admin by providing administrative credentials.



After logging in as admin, please refer to this authorize tag for evaluation and display the following output.