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
并覆盖authentication
和supports
方法,然后注入到AuthenticationManager
。在过滤器
attemptAuthentication
方法通常是让authentication
(例如UsernamePasswordFilter
获取从请求username
和password
,然后生成一个UsernamePasswordAuthenticationToken
到AuthenticationManager
)
supports
方法测试AuthenticationProvider
是否可以用来做验证。(例如DaoAuthenticationProvider
支持UsernamePasswordAuthenticationToken
)
authenticate
方法用于进行身份验证(例如,DaoAuthenticationProvider
通过用户名获取真实密码,然后与用户比较输入),则此方法应返回已经过身份验证的Authentication
(例如UsernamePasswordAuthenticationToken
),并且此身份验证应包含用户权限(可用于hasRole('xxx')
)或使用详细信息等。
attemptAuthentication
成功后,Authentication
将设置为SecurityContextHolder
。然后你可以使用hasRole('xx')
,或其他东西。