Spring Security at Method Level

Spring Security at Method Level, 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 at Method Level

Spring Security at Method Level

Apart from authentication, spring security also check authorization of the logged in user. After login which user is authorize to access the resource is done on the bases of user's ROLE.

At the time of creating user in WebSecurityConfig class, we can specify user?s ROLE as well.

Security applied on a method restricts to unauthorized user and allow only authentic user.

Let's see an example. First create a maven project by providing details.

This project initially look like this:

Spring Security Configuration

Now, configure the application to protect from unauthorized and unauthentic users. It requires four Java files that are given below, create a package com.javatpoint and place all these files inside it.

// AppConfig.java

This class is used to set view suffix and prefix with the help of view resolver.

  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. @EnableWebMvc    
  9. @Configuration    
  10. @ComponentScan({ "com.javatpoint.controller.*" })    
  11. public class AppConfig {    
  12.     @Bean    
  13.     public InternalResourceViewResolver viewResolver() {    
  14.         InternalResourceViewResolver viewResolver    
  15.                           = new InternalResourceViewResolver();    
  16.         viewResolver.setViewClass(JstlView.class);    
  17.         viewResolver.setPrefix("/WEB-INF/views/");    
  18.         viewResolver.setSuffix(".jsp");    
  19.         return viewResolver;    
  20.     }    
  21. }  

// MvcWebApplicationInitializer.java.java

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

// SecurityWebApplicationInitializer.java

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

// WebSecurityConfig.java

This class is used to create user and set their authentication. Each time login is required when user want to access into the application.

  1. package com.tpoint;  
  2. import org.springframework.context.annotation.*;  
  3. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;  
  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. @EnableGlobalMethodSecurity(prePostEnabled=true)  
  13. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {    
  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("irfan").password("user123").roles("USER").build());  
  20. manager.createUser(users.username("admin").password("admin123").roles("ADMIN").build());  
  21.      return manager;  
  22.     }   
  23. @Override    
  24. protected void configure(HttpSecurity http) throws Exception {    
  25.       http.authorizeRequests().  
  26.       antMatchers("/index","/").permitAll()  
  27.       .antMatchers("/admin","/user").authenticated()  
  28.       .and()  
  29.       .formLogin()  
  30.       .and()  
  31.       .logout()  
  32.       .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));  
  33. }    
  34. }    

Controller

Create a controller HomeController and place into com.javatpoint.controller package.

// HomeController.java

  1. package com.tpoint.controller;  
  2. import org.springframework.security.access.prepost.PreAuthorize;  
  3. import org.springframework.stereotype.Controller;    
  4. import org.springframework.web.bind.annotation.RequestMapping;    
  5. import org.springframework.web.bind.annotation.RequestMethod;  
  6. import org.springframework.web.bind.annotation.ResponseBody;  
  7. @Controller    
  8. public class HomeController {    
  9.     @RequestMapping(value="/"method=RequestMethod.GET)    
  10.     public String index() {    
  11.         return "index";    
  12.     }    
  13.     @RequestMapping(value="/user"method=RequestMethod.GET)    
  14.     public String user() {    
  15.        return "admin";  
  16.     }    
  17.     @RequestMapping(value="/admin"method=RequestMethod.GET)    
  18.     public String admin() {    
  19.         return "admin";    
  20.     }  
  21.     // Only, a person having ADMIN role can access this method.  
  22.     @RequestMapping(value="/update"method=RequestMethod.GET)   
  23.     @ResponseBody  
  24.     @PreAuthorize("hasRole('ROLE_ADMIN')")  
  25.     public String update() {    
  26.         return "record updated ";    
  27.     }  
  28. }   

View

Create following views (JSP pages) to produce output for the user. Place all the views into WEB-INF/views folder.

// index.jsp

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

// admin.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. <span style="color: green">Login Successful!</span> ? <a href="logout" style="text-decoration: none;">logout</a>  <br> <br>  
  8. <a href="update" style="text-decoration: none;">Update Record</a>  
  9. </body>    
  10. </html>   

Package Dependencies

Following are the dependencies that are required to create this project.

  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>springmethod</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-config -->  
  28. <dependency>  
  29.     <groupId>org.springframework.security</groupId>  
  30.     <artifactId>spring-security-config</artifactId>  
  31.     <version>5.0.4.RELEASE</version>  
  32. </dependency>  
  33. <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->  
  34.         <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->    
  35. <dependency>    
  36.     <groupId>javax.servlet</groupId>    
  37.     <artifactId>javax.servlet-api</artifactId>    
  38.     <version>3.1.0</version>    
  39.     <scope>provided</scope>    
  40. </dependency>    
  41. <dependency>    
  42.     <groupId>javax.servlet</groupId>    
  43.     <artifactId>jstl</artifactId>    
  44.     <version>1.2</version>    
  45. </dependency>    
  46. <!-- https://mvnrepository.com/artifact/org.springframework/spring-framework-bom -->  
  47. </dependencies>    
  48.   <build>    
  49.     <plugins>    
  50.         <plugin>    
  51.             <groupId>org.apache.maven.plugins</groupId>    
  52.             <artifactId>maven-war-plugin</artifactId>    
  53.             <version>2.6</version>  
  54.                    <configuration>    
  55.                 <failOnMissingWebXml>false</failOnMissingWebXml>    
  56.             </configuration>    
  57.         </plugin>    
  58.     </plugins>    
  59.   </build>    
  60. </project>  

Project Structure

After adding all the above files, our project looks like this:

Run Server

Output:

First login as ADMIN

After login,

Click on update record and see, record is updated because the user's role is ADMIN.

User Login

Now, login as user.

Now, click on update record and see server decline the access because the user's role is USER.