在 Spring Boot 中使用 Spring Security

1. 添加依赖
在项目的 `pom.xml` 文件中添加 Spring Security 的依赖:

<dependencies>
    <!-- Spring Security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
</dependencies>

2. 配置安全策略
在项目的配置类中配置安全策略,可以通过继承 `WebSecurityConfigurerAdapter` 并重写其中的方法来实现:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/home")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER");
    }
}

上述代码配置了如下安全策略:
- `/public/**` 路径下的请求允许所有用户访问
- 其他路径下的请求需要身份验证
- 登录页面为 `/login`,登录成功后跳转到 `/home
`- 支持注销操作
3. 创建登录页面和首页
在项目中创建登录页面 `login.html` 和首页 `home.html`。
4. 运行应用程序
启动应用程序,并访问 `http://localhost:8080/login` 进行登录。

基于 GPT 生成。

posted @ 2023-07-07 20:30  dersdysbiokecu  阅读(58)  评论(0)    收藏  举报