Spring Security的授权和身份验证

问题描述:

我有一个基于Spring构建的Web服务。我目前正在验证使用Spring Security的如下:Spring Security的授权和身份验证

@Configuration 
@EnableGlobalMethodSecurity(securedEnabled=true) 
@EnableWebSecurity 

public class ServerSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private Properties properties; 

    private static final String ALL_URI = "/v1/**"; 
    private static final String HEALTH_URI = "/v1/healthCheck"; 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.addFilterBefore(getFilter(), BasicAuthenticationFilter.class); 
     http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 
     http.authorizeRequests() 
       .antMatchers(HEALTH_URI).permitAll() 
       .anyRequest().authenticated(); 
     http.csrf().disable(); 
    } 

    private AuthenticationFilter getFilter() { 
     return new AuthenticationFilter(properties.getKey()); 
    } 
} 

AuthenticationFilter类扩展AbstractAuthenticationProcessingFilter和执行实际的验证。如果我想将授权添加到我的安全性中,我是否只需在AuthenticationFilter的attemptAuthentication方法中进行这些检查?还是有更好的方法来做到这一点?我理解的方式是授权和认证应该独立完成。您首先进行身份验证,然后验证权限。所以,我会假设在Spring Security中会有更好的方法来进行授权,而不是将其添加到attemptAuthentication方法中。

你需要一个AuthenticationProvider做身份验证,实现AuthenticationProvider并覆盖authenticationsupports方法,然后注入到AuthenticationManager。在过滤器

attemptAuthentication方法通常是让authentication(例如UsernamePasswordFilter获取从请求usernamepassword,然后生成一个UsernamePasswordAuthenticationTokenAuthenticationManager

supports方法测试AuthenticationProvider是否可以用来做验证。(例如DaoAuthenticationProvider支持UsernamePasswordAuthenticationToken

authenticate方法用于进行身份验证(例如,DaoAuthenticationProvider通过用户名获取真实密码,然后与用户比较输入),则此方法应返回已经过身份验证的Authentication(例如UsernamePasswordAuthenticationToken),并且此身份验证应包含用户权限(可用于hasRole('xxx'))或使用详细信息等。

attemptAuthentication成功后,Authentication将设置为SecurityContextHolder。然后你可以使用hasRole('xx'),或其他东西。