繁体   English   中英

Spring 引导安全 - 如果缺少授权 header,则使用 Cookies 中的令牌

[英]Spring Boot Security - Use token from Cookies if Authorization header missing

我目前针对我的授权服务器的 JWK 验证我的请求。 我在 spring-boot 2.3 上使用spring-boot-starter-oauth2-resource-server package。 JWT 从Authorization: Bearer <token> header 中取出并针对 JWK 端点进行验证。 我的安全配置如下所示:

安全配置.java

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  protected Environment env;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/logs").permitAll();
    http.authorizeRequests().antMatchers("/", "/api/**").authenticated();
    http.oauth2ResourceServer().jwt();
  }
}

应用程序属性

spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://auth.work.com/v1/jwk

外部用户没有Authorization: ... header 在他们的请求中,而是有以下 2 个 cookies 构成 JWT:

auth.token_type = Bearer
auth.access_token = <token>

有没有办法从 cookies 中提取 JWT 并在授权服务器上进行Authorization: ... header 丢失? 我可以在尝试授权之前提取 cookies 并在请求中添加 header 吗? 或者它甚至可能是身份验证链中的第二种方法。

我发现了自定义令牌解析器并最终创建了一个来验证 header 和 cookie。 我不确定这是否是最干净的解决方案,但它确实有效。

我对此的唯一问题是它不会自动验证Authorization: Bearer... header 了,所以我也必须为其添加代码。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/logs").permitAll();
    http.authorizeRequests().antMatchers("/", "/api/**").authenticated();
    http.oauth2ResourceServer().jwt().and().bearerTokenResolver(this::tokenExtractor);
  }

  public String tokenExtractor(HttpServletRequest request) {
    String header = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (header != null)
      return header.replace("Bearer ", "");
    Cookie cookie = WebUtils.getCookie(request, "auth.access_token");
    if (cookie != null)
      return cookie.getValue();
    return null;
  }
}

我认为您可以使用自定义过滤器,拦截请求并从 HttpServletRequest 获取 cookies。

@Override
public void doFilter(
  ServletRequest request, 
  ServletResponse response,
  FilterChain chain) throws IOException, ServletException {
    Cookie[] cookies = request.getCookies();
    // Your validation logic
}

只需将其添加到 Spring 安全过滤器链即可。

更多细节如何在这里做: https://www.baeldung.com/spring-security-custom-filter

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM