brief introduction
As one of the Spring family bucket components, Spring Security is a security component that addresses two main issues:
- Authentication: Verify user name and password;
- Authorization: The permissions for different URLs are different and can only be accessed if the authenticated user has the required permissions for a URL.
At the bottom of Spring Security is a filter that intercepts URLs, which corresponds to classes in Java; therefore, it is called coarse-grained authorization verification, which verifies that the URL is authorized by the current user.
Introduction
Create Project
Create a Spring Boot project with Idea and check the components you want:
- Spring Web
- Spring Security
Or add a dependency after creating the project:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
JSP is used as a template here. For information on how to use JSP as a template in Spring Boot, visit: https://www.cnblogs.com/cloudfloating/p/11787222.html
WebSecurityConfig
package top.cloudli.demo.security; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled=true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { PasswordEncoder encoder = new BCryptPasswordEncoder(); auth.inMemoryAuthentication() .passwordEncoder(encoder) .withUser("root") .password(encoder.encode("root@123456")) .roles("ROOT", "USER") .and() .withUser("user") .password(encoder.encode("user@123456")) .roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/css/**") .permitAll() // css does not require validation .anyRequest() .authenticated() // All other pages need validation .and() .formLogin() // Use the default login page .and() .exceptionHandling() .accessDeniedPage("/401") // Pages jumped without permission .and() .logout(); } }
- The @EnableWebSecurity comment enables validation;
- The @EnableGlobalMethodSecurity(prePostEnabled=true) annotation allows us to use @PreAuthorize in the controller's methods for privilege splitting.
Here, two users are created and stored in memory, root with ROOT and USER privileges and user with USER privileges only.
The fromLogin() method can then call loginPage() to specify a custom login page, where the default login page is used.
Write Page
1.index.jsp, accessible to all authenticated users:
<%-- Pages accessible to any authenticated user --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Spring Security Demo Application</title> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <div class="content"> <h1>Spring Security In Memory Authentication</h1> <h2>This is a protected page ( ROLE_USER). </h2> </div> </body> </html>
2.root.jsp, accessible only to users with ROOT privileges:
<%-- Need ROLE_ROOT Pages accessible only --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Root Page</title> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <div class="content"> <h1>Root Page</h1> <h2>You are accessing a protected page ( ROLE_ROOT). </h2> </div> </body> </html>
3.401.jsp, page to jump to without permission:
<%-- Pages that jump when permissions are insufficient --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>401 Unauthorized</title> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body class="error"> <div class="content"> <h1>401 Unauthorized!</h1> <h2>You do not have permission to access this page.</h2> </div> </body> </html>
Controller
package top.cloudli.demo.controller; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class DemoController { @PreAuthorize("hasAnyAuthority('ROLE_USER')") @GetMapping("/") public String index() { return "index"; } @PreAuthorize("hasAnyAuthority('ROLE_ROOT')") @GetMapping("/root") public String root() { return "root"; } @GetMapping("/401") public String accessDenied() { return "401"; } }
The @PreAuthorize annotation specifies the permissions required to access the page, where they are prefixed with ROLE_
Run
Visit http://localhost:8080/will enter the login page (the default login page for Spring Security is used here):
Logging in with the memory user you just created will return to the index page:
Access http://localhost:8080/root, jump to page 401 because user does not have ROLE_ROOT privilege:
Accessing http://localhost:8080/logout will enter the default logout page:
The login and logout pages here can use custom pages that simply submit data to/login or/logout through a PSOT request.