gpt4 book ai didi

spring-security - 如何在 spring boot oauth2 资源服务器中使用自定义 auth header

转载 作者:行者123 更新时间:2023-12-05 01:27:02 26 4
gpt4 key购买 nike

我正在配置 spring cloud api 网关以支持多个安全链。为此,我使用了多个安全过滤器链,这些链会在特定安全 header 存在时触发:

  1. 已经使用 Authorization header 的旧版本
  2. 以及与外部 IDP 集成的新实现。该解决方案利用资源服务功能。对于我想使用的这条链,可以说是“New-Auth” header 。

如果我调整我当前的设置以在存在授权 header 时触发第二个 (idp) 链(并使用 IDP token 进行调用),那么一切正常。通过这种方式,安全链会根据 idp jwk 验证它在授权 header 中期望的 token 。但是此 header 已保留用于旧版身份验证。

我想我需要一种方法来为 spring 资源服务器链指向一个要查找的新 header 名称。

我的安全依赖项:

implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'

我的配置

@EnableWebFluxSecurity
public class WebSecurityConfiguration {

// ...

@Bean
@Order(1)
public SecurityWebFilterChain iamAuthFilterChain(ServerHttpSecurity http) {
ServerWebExchangeMatcher matcher = exchange -> {
HttpHeaders headers = exchange.getRequest().getHeaders();
List<String> strings = headers.get(SurpriseHeaders.IDP_AUTH_TOKEN_HEADER_NAME);
return strings != null && strings.size() > 0
? MatchResult.match() : MatchResult.notMatch();
};

http
.securityMatcher(matcher)
.csrf().disable()
.authorizeExchange()
.pathMatchers(navigationService.getAuthFreeEndpoints()).permitAll()
.anyExchange().authenticated()
.and()
.oauth2ResourceServer(OAuth2ResourceServerSpec::jwt)
.oauth2ResourceServer().jwt().jwkSetUri(getJwkUri())
.and()
.and()
.addFilterAt(new LoggingFilter("idpAuthFilterChain"), SecurityWebFiltersOrder.FIRST)
.addFilterAfter(new IdpTokenExchangeFilter(authClientService), SecurityWebFiltersOrder.AUTHENTICATION)
;
return http.build();
}

}

肮脏的解决方案:

我们可以添加一些过滤器来编辑请求,并将传入的“New-Auth” header 复制为 security filter chain 开头的“Authorization” header 。

看起来可行,但我相信它应该是更好的方法。

最佳答案

您可以为您的 oauth2ResourceServer 配置指定一个 ServerAuthenticationConverter,如下所示:

http
.oauth2ResourceServer((resourceServer) -> resourceServer
.bearerTokenConverter(customBearerTokenAuthenticationConverter())
.jwt()
);

ServerAuthenticationConverter customBearerTokenAuthenticationConverter() {
ServerBearerTokenAuthenticationConverter tokenAuthenticationConverter = new ServerBearerTokenAuthenticationConverter();
tokenAuthenticationConverter.setBearerTokenHeaderName("New-Auth");
return tokenAuthenticationConverter;
}

关于spring-security - 如何在 spring boot oauth2 资源服务器中使用自定义 auth header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69836879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com