spring云网关+spring安全和多个oauth2客户端



我将在一些现有的web应用程序之前放置一个spring云网关,这些应用程序已经使用keycapture作为其身份提供者,我希望在网关内验证传入请求。目前,每个web应用程序都已经配置了正确的客户端id,并使用正确的值重定向到密钥斗篷。现在,网关必须执行授权代码流,而不是每个应用程序,因此它必须提前知道哪个客户端是哪个请求的url。所以,我一直在研究如何实现它,但我仍然没有任何合适的解决方案。解决方案是什么?或者,这样做真的是一种门户责任吗?

实际上,我找到了一个解决方案,但我不确定它是否是最好的。

@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange().pathMatchers("/actuator/**").permitAll().and()
.authorizeExchange().anyExchange().authenticated().and().csrf().disable().oauth2Login()
.and()
.exceptionHandling().authenticationEntryPoint(createEntryPoints())
.and()
.oauth2ResourceServer().jwt()
.jwtAuthenticationConverter(grantedAuthoritiesExtractor());
return http.build();
}
public ServerAuthenticationEntryPoint createEntryPoints() {
List<DelegateEntry> entryPoints = new ArrayList<>();
entryPoints
.add(new DelegateEntry(ServerWebExchangeMatchers.pathMatchers("/app1"),
new RedirectServerAuthenticationEntryPoint("/oauth2/authorization/client1")));
//other clients will be added here
DelegatingServerAuthenticationEntryPoint defaultEntryPoint = new DelegatingServerAuthenticationEntryPoint(
entryPoints);
defaultEntryPoint.setDefaultEntryPoint(new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED));
return defaultEntryPoint;
}

因此client1将用于/app1,依此类推。正如我之前所说,我不确定,也许有更好的解决方案。

您可以查看以下答案:

如何创建Spring Cloud网关过滤器来添加客户端凭据访问令牌?

为了支持不同的客户端ID(机密、令牌uri等(,您只需在spring.security.oauth2.client.registration部分中定义多个配置,并在Oauth2ClientGatewayFilter类中使客户端ID动态:

String clientId = ...
OAuth2AuthorizeRequest oAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(clientId)
.principal("myPrincipal").build();

最新更新