echobom / notes

MIT License
0 stars 0 forks source link

Spring Security #13

Open echobom opened 7 months ago

echobom commented 7 months ago

AuthenticationManager 是 Spring Security 提供的核心接口之一,用于验证用户的身份认证请求。它是一个处理身份验证的中央组件,负责接收用户的凭据(例如用户名和密码),并进行身份验证的处理。

AuthenticationManager 接口定义了以下方法:

在 Spring Security 中,AuthenticationManager 接口有一个默认的实现类 ProviderManager,它可以处理多个身份验证提供者(AuthenticationProvider)。AuthenticationProvider 是另一个核心接口,用于执行实际的身份验证逻辑。

AuthenticationManager 的典型用法是在配置类中进行配置,并注入到其他组件中,例如授权服务器、资源服务器或者 Web 应用程序的安全配置中。

以下是一个简单的示例,展示了如何配置和使用 AuthenticationManager

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/user/**").hasRole("USER")
            .anyRequest().authenticated()
            .and()
            .formLogin();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

在上述示例中,我们创建了一个名为 SecurityConfig 的配置类,继承自 WebSecurityConfigurerAdapter。在 configure(AuthenticationManagerBuilder auth) 方法中,我们配置了一个自定义的 UserDetailsService,并指定了密码编码器(PasswordEncoder)。这样,Spring Security 将使用该 UserDetailsService 来获取用户的详细信息,并使用密码编码器来验证密码。

configure(HttpSecurity http) 方法中,我们配置了基于角色的访问控制规则。只有具有 "ADMIN" 角色的用户才能访问 "/admin/" 路径,具有 "USER" 角色的用户才能访问 "/user/" 路径,其他所有请求都需要进行身份验证。同时,我们启用了基于表单的登录。

SecurityConfig 类中,我们还重写了 authenticationManagerBean() 方法,并用 @Bean 注解标记,以将 AuthenticationManager 注入到其他组件中使用。

通过配置和使用 AuthenticationManager,我们可以实现自定义的身份验证逻辑,并将其应用于 Spring Security 中的各个组件,以确保请求的身份验证和安全性。

echobom commented 7 months ago

@EnableGlobalMethodSecurity 是一个注解,它用于在 Spring Security 中启用方法级别的安全性。

通过在配置类上添加 @EnableGlobalMethodSecurity 注解,可以使用不同的属性来配置方法级别的安全性。以下是一些常用的属性:

例如,以下是一个使用 @EnableGlobalMethodSecurity 的示例:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // ...

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // ...
    }
}

在上述示例中,SecurityConfig 类上添加了 @EnableGlobalMethodSecurity 注解,并设置了 prePostEnabled = true, securedEnabled = true,启用了 @PreAuthorize@PostAuthorize@Secured 注解。

启用方法级别的安全性后,您可以在方法上使用注解来限制对方法的访问。例如:

@Service
public class MyService {

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public void adminOnlyMethod() {
        // ...
    }

    @Secured("ROLE_USER")
    public void userOnlyMethod() {
        // ...
    }

    @PostAuthorize("returnObject.userId == authentication.principal.username")
    public MyObject getMyObject() {
        // ...
    }
}

在上述示例中,adminOnlyMethod() 方法使用 @PreAuthorize 注解,要求调用者具有 ROLE_ADMIN 角色才能访问该方法。

userOnlyMethod() 方法使用 @Secured 注解,要求调用者具有 ROLE_USER 角色才能访问该方法。

getMyObject() 方法使用 @PostAuthorize 注解,对方法的返回值进行进一步的授权检查,确保只有返回对象的 userId 与当前用户的用户名匹配时,才允许返回结果。

通过使用 @EnableGlobalMethodSecurity 和相应的注解,可以在方法级别上实现细粒度的安全性控制,确保只有具备适当权限和角色的用户才能访问受保护的方法。