Home >Java >javaTutorial >How SpringBoot quickly integrates SpringSecurity
Spring Security is a security framework based on the Spring framework, which provides a set of lightweight APIs and tools to implement common security functions such as authentication, authorization, and attack prevention. It supports various authentication methods, such as basic authentication, form authentication, OAuth3.0 and OpenID Connect, etc. Developers can customize it according to the needs of the application because Spring Security has a large number of configurable options. Spring Security has become one of the most widely used security frameworks for Java enterprise applications.
The main principle of Spring Security is to protect application resources through the filter chain. Different security functions are taken care of by different filters in the filter chain, such as authentication, authorization, attack defense, etc.
When a request reaches the application, it will first be intercepted by the outermost filter. This filter passes the request to the next filter and performs some pre-processing before that, such as logging and cross-origin request handling, etc. Each filter is executed sequentially in the filter chain until the innermost filter has processed the request and returned a response.
Spring Security protects application resources by configuring filter chains. Each filter has different responsibilities, such as:
(1) AuthenticationFilter: Authentication filter, used to authenticate users.
(2)AuthorizationFilter: Authorization filter, used to check whether the user has permission to access a resource.
(3) CsrfFilter: Prevent cross-site request forgery (CSRF) filter, used to prevent CSRF attacks.
(4)ExceptionTranslationFilter is a filter that handles security-related exceptions and is responsible for converting exceptions.
(5) SessionManagementFilter: Session management filter, used to manage user sessions.
Developers can customize their own security policies based on the APIs and tools provided by Spring Security and add them to the filter chain. When an application receives a request, it will protect its resources according to these security policies.
Add dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
Configure Spring Security
# 设置默认用户 spring.security.user.name=user spring.security.user.password=pass # 关闭CSRF保护 spring.security.csrf.enabled=false
Write security configuration class. Write a security configuration class to configure Spring Security. This class should extend WebSecurityConfigurerAdapter and override some methods to configure security.
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // 配置用户信息 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}pass").roles("USER"); } // 配置HTTP请求安全性 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/public/**").permitAll() // 允许/public/**路径下的所有请求 .anyRequest().authenticated() // 所有其他请求都需要身份验证 .and() .formLogin() // 启用表单登录 .loginPage("/login") // 指定登录页面 .defaultSuccessUrl("/", true) // 登录成功后重定向到主页 .permitAll() // 允许所有用户访问登录页面 .and() .logout() // 启用注销 .logoutUrl("/logout") // 注销URL .logoutSuccessUrl("/login") // 注销成功后重定向到登录页面 .permitAll(); // 允许所有用户注销 } }
In the above configuration, we configured an in-memory authentication (using username and password) and HTTP request security (allowing requests under certain paths, requiring authentication for all other requests, and Turn on form login and logout).
Writing Controller. Finally, you need to write a controller to handle login and logout requests.
@Controller public class LoginController { // 处理登录请求 @GetMapping("/login") public String login() { return "login"; } // 处理注销请求 @PostMapping("/logout") public String logout() { return "redirect:/login?logout=true"; } }
We define a method named login() in the code to process the login page request and return a template named login. The logout() method is used to handle the logout request and redirect to the login page.
Write html template. Finally, we need to write a template called login.html to render the login page.
<!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h2>Login</h2> <form action="/login" method="post"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username" required autofocus /> </div> </form> </body> </html>
The above is the detailed content of How SpringBoot quickly integrates SpringSecurity. For more information, please follow other related articles on the PHP Chinese website!