我使用Spring 4和Spring Security,自定义GenericFilterBean和AuthenticationProvider实现。除了用于创建新会话的URL之外,我主要保护URL: / v2 / session (例如,基于用户名和密码登录并返回要使用的Auth Token在后续请求身份验证的请求中配置如下:
@Configuration
@ComponentScan(basePackages={"com.api.security"})
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ApiAuthenticationProvider apiAuthenticationProvider;
@Autowired
private AuthTokenHeaderAuthenticationFilter authTokenHeaderAuthenticationFilter;
@Autowired
private AuthenticationEntryPoint apiAuthenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(apiAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(authTokenHeaderAuthenticationFilter, BasicAuthenticationFilter.class) // Main auth filter
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests()
.antMatchers(HttpMethod.POST, "/v2/session").permitAll()
.anyRequest().authenticated();
http.exceptionHandling()
.authenticationEntryPoint(apiAuthenticationEntryPoint);
}
}
authTokenHeaderAuthenticationFilter 会在每个请求上运行,并从请求标头中获取令牌:
/**
* Main Auth Filter. Always sets Security Context if the Auth token Header is not empty
*/
@Component
public class AuthTokenHeaderAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final String token = ((HttpServletRequest) request).getHeader(RequestHeaders.AUTH_TOKEN_HEADER);
if (StringUtils.isEmpty(token)) {
chain.doFilter(request, response);
return;
}
try {
AuthenticationToken authRequest = new AuthenticationToken(token);
SecurityContextHolder.getContext().setAuthentication(authRequest);
}
} catch (AuthenticationException failed) {
SecurityContextHolder.clearContext();
return;
}
chain.doFilter(request, response); // continue down the chain
}
}
自定义 apiAuthenticationProvider 将尝试根据标头中提供的令牌验证所有请求,如果身份验证不成功,则抛出AccessException,客户端将收到HTTP 401响应:
@Component
public class ApiAuthenticationProvider implements AuthenticationProvider {
@Autowired
private remoteAuthService remoteAuthService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
AuthenticationToken authRequest = (AuthenticationToken) authentication;
String identity = null;
try {
identity = remoteAuthService.getUserIdentityFromToken(authRequest.getToken());
} catch (AccessException e) {
throw new InvalidAuthTokenException("Cannot get user identity from the token", e);
}
return new AuthenticationToken(identity, authRequest.getToken(), getGrantedAuthorites());
}
}
这对于需要身份验证的请求非常有效。这适用于 / v2 / session 请求,但不包含Authentication Header。但是,对于 / v2 / session 请求,在标头中(或在Cookie中有一个过期的Auth标记 - 代码示例中未显示;有时可能会发生这种情况)客户端没有清除标头或继续发送带有请求的cookie)安全上下文将被初始化, apiAuthenticationProvider 将抛出异常并通过HTTP 401响应客户。
由于 / v2 / session 已配置为
http.authorizeRequests()
.antMatchers(HttpMethod.POST, "/v2/session").permitAll()
我希望Spring Security在调用ApiAuthenticationProvider.authenticate()之前确定它。过滤器或身份验证提供程序应该忽略/不为配置为permitAll()的URL抛出异常的方式是什么?
答案 0 :(得分:14)
在执行请求授权检查之前,会触发Spring安全筛选器。要使授权检查起作用,假定请求已通过过滤器并且已设置Spring安全上下文(或不设置,具体取决于是否已传入身份验证凭据)。
在过滤器中,如果没有令牌,则检查是否继续进行过滤器链处理。不幸的是,如果是,那么它将被传递给您的提供者进行身份验证,这会引发异常,因为令牌已经过期,因此您将获得401。
您最好的选择是绕过您认为公开的网址的过滤器执行。您可以在过滤器本身或配置类中执行此操作。将以下方法添加到SecurityConfig
类:
@Override
public void configure(WebSecurity webSecurity) {
webSecurity.ignoring().antMatchers(HttpMethod.POST, "/v2/session");
}
这样做会完全绕过AuthTokenHeaderAuthenticationFilter
网址POST /v2/sessions
。