簡體   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