Spring URL 的安全性,使用 permitAll() 和过期的授权令牌

Spring Security for URL with permitAll() and expired Auth Token

我正在使用 Spring 4 和 Spring 安全、自定义 GenericFilterBean 和 AuthenticationProvider 实现。除了 URL 之外,我大部分都获得了 URLs 来创建新的 session:/v2/session(例如根据用户名和密码登录,returnsAuth 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 在每个请求上运行并从请求 header 中获取令牌:

/**
 * 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 将尝试根据 header 中提供的令牌对所有请求进行身份验证,如果身份验证是不成功 - 抛出 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 请求,其中没有身份验证 Header。但是,对于 /v2/session 请求,在 header(或在 cookie 中 - 不代码示例中显示;如果客户端未清除 headers 或继续发送带有请求的 cookie,有时可能会发生这种情况)安全上下文将被初始化并且 apiAuthenticationProvider 将抛出异常并用 HTTP 401 响应客户端。

由于/v2/session已配置为

http.authorizeRequests()
        .antMatchers(HttpMethod.POST, "/v2/session").permitAll()

我希望 Spring 安全部门在调用 ApiAuthenticationProvider.authenticate() 之前确定这一点。过滤器或身份验证提供程序 ignore/not 为配置为 permitAll() 的 URL 抛出异常的方式应该是什么?

Spring 安全过滤器在执行请求授权检查之前被触发。为了使授权检查起作用,假设请求已通过过滤器并且已设置 Spring 安全上下文(或未设置,取决于是否已传入身份验证凭据)。

在您的过滤器中,如果令牌不存在,您会检查继续进行过滤器链处理。不幸的是,如果是,那么它将被传递给您的提供商进行身份验证,这会引发异常,因为令牌已过期,因此您将收到 401。

您最好的选择是绕过您认为 public 的 URL 的过滤器执行。您可以在过滤器本身或您的配置中执行此操作 class。将以下方法添加到您的 SecurityConfig class:

@Override
public void configure(WebSecurity webSecurity) {
  webSecurity.ignoring().antMatchers(HttpMethod.POST, "/v2/session");
}

这样做的目的是完全绕过 AuthTokenHeaderAuthenticationFilter POST /v2/sessions URL。