簡體   English   中英

如何使用 spring 安全自定義授權評估 spring 雲網關中的 HTTP POST 負載

[英]How can I evaluate the HTTP POST payload in spring cloud gateway using spring security custom authorization

我正在嘗試保護我的一些 spring 雲網關路由:

  1. 用戶必須使用 OAUTH2 進行身份驗證才能使用這些路由(如果沒有 -> 響應 http 401)
  2. JWT 訪問令牌必須在“scp”聲明中包含一個特定的值(在我的例子中是“2fa”)(如果不是,請回復 http 403)
  3. JSON 有效載荷包含一個屬性“user”,該屬性必須與 JWT 訪問令牌中的“sub”聲明具有相同的值。 (如果沒有,請回復 http 403)

閱讀文檔我發現了如何設置 1. 和 2. 不幸的是,關於如何實現 3. 的信息似乎很少。

我在哪里可以找到一個有效的例子?

這是來自 application.yaml 文件的我的 spring 安全設置:

...
spring:
  profiles: production

  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: ${AUTH_URL}/oidc
          jwk-set-uri: ${AUTH_URL}/oidc/jwks.json
...

我的 SecurityWebFilterChain 的配置:

...
 @Bean
  @Order(Ordered.HIGHEST_PRECEDENCE - 3)
  public SecurityWebFilterChain secondFactorScopeApiHttpSecurity(ServerHttpSecurity http) {
    final ServerWebExchangeMatcher baseScopeEndpointsMatcher = new OrServerWebExchangeMatcher(
        new PathPatternParserServerWebExchangeMatcher("/api/fhir"),
        new PathPatternParserServerWebExchangeMatcher("/api/fhir/List**"),
        new PathPatternParserServerWebExchangeMatcher("/api/fhir/Observation**")
    );

    http.securityMatcher(baseScopeEndpointsMatcher)
        .authorizeExchange(exchanges -> exchanges.anyExchange().hasAuthority("SCOPE_2fa"))
        .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt);
    return http.build();
  }
...

我希望用戶看到 HTTP 403,以防負載“用戶”屬性與 JWT 中的子聲明不匹配。

你想要實現的是資源服務器上的一項簡單任務,在我看來,資源訪問控制是資源服務器的責任,而不是網關,特別是如果訪問決策涉及資源本身。

我只想讓網關對 OAuth2 透明:保留請求授權 header 以及響應狀態代碼不變。

我在該系列教程中有一些示例,這些示例逐步構建為基於角色的高級訪問控制。 完成前 3 個步驟需要不到一個小時的時間:

  • 第一次使用spring-boot-starter-oauth2-resource-server演示資源服務器安全配置(到目前為止你在網關上實現的)
  • 第 2 部分展示了如何將JwtAuthenticationToken替換為您選擇的公開強類型私有聲明的實現。 它還大大減少了 Java conf 與我在 spring-boot 周圍創建的薄包裝之一。
  • 第三次演示安全 SpEL 定制以編寫類似
@GetMapping("/on-behalf-of/{username}")
@PreAuthorize("is(#username) or isNice() or onBehalfOf(#username).can('greet')")
public String getGreetingFor(@PathVariable("username") String username) {
   ... 
} 

當然,在你的情況下,你會使用像myControllerMethod(@RequestBody MyDto dto, Authentication auth)這樣的簽名和像#dto.sub eq #auth.name這樣的表達式,但你明白了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM