Home > Java > javaTutorial > body text

How SpringBoot quickly integrates SpringSecurity

WBOY
Release: 2023-05-16 21:56:28
forward
958 people have browsed it

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

2. The principle of SpringSecurity

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.

3. SpringBoot integrates SpringSecurity

Add dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
Copy after login

Configure Spring Security

# 设置默认用户
spring.security.user.name=user
spring.security.user.password=pass

# 关闭CSRF保护
spring.security.csrf.enabled=false
Copy after login

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(); // 允许所有用户注销
    }
}
Copy after login

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";
    }
}
Copy after login

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>
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!