Spring Security 是一个功能强大的Java安全框架,用于保护Web应用程序。以下是一些关于Spring Security的基础知识和使用方法。

快速开始

要开始使用Spring Security,您需要添加以下依赖到您的 pom.xml 文件中:

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

基本配置

在Spring Security中,您需要创建一个继承自 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")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
}

访问控制

您可以使用 @PreAuthorize@PostAuthorize 注解来控制方法级别的访问。

@PreAuthorize("hasRole('ADMIN')")
public void adminMethod() {
    // 只有管理员可以访问此方法
}

用户认证

Spring Security 支持多种用户认证方式,包括数据库、LDAP、OAuth2等。

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

保护Web资源

要保护Web资源,您可以使用 @Secured 注解。

@Secured("ROLE_USER")
public String protectedResource() {
    return "This is a protected resource.";
}

扩展阅读

如果您想了解更多关于Spring Security的信息,请访问Spring Security官方文档

Spring Security Logo