我想将 Spring Cloud Gateway 配置为具有授权代码流程的 oauth2 客户端 我的网关应该是无状态的(它不应该维护任何会话) 成功登录后我需要返回令牌 例如: 如果我点击 /login 端点,它应该重定向到 /oauth2/authorization/spring ,并且应该重定向到授权服务器的 /oauth2/authorize 端点,然后它应该在成功登录后显示登录页面,它应该返回令牌
用Spring Cloud Gateway和Spring授权服务器可以实现吗?
是的,可以将 Spring Cloud Gateway 配置为具有授权代码流的 OAuth 2.0 客户端,同时保持无状态性。实现这一目标涉及的关键组件是用于处理路由的 Spring Cloud Gateway 和支持 OAuth 2.0 身份验证的 Spring Security。
xyz.yaml:
spring:
cloud:
gateway:
routes:
- id: oauth2-login
uri: http://authorization-server/oauth2/authorization/spring
predicates:
- Path=/login
filters:
- RewritePath=/login, /oauth2/authorization/spring
Java:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests ->
authorizeRequests
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(oauth2Login ->
oauth2Login
.authorizationEndpoint(authorizationEndpoint ->
authorizationEndpoint.baseUri("/oauth2/authorization")
)
);
}
}
3:令牌检索: 身份验证成功后,Spring Security 将处理令牌的检索。 您可以在应用程序代码中访问令牌。
@RestController
public class TokenController {
@GetMapping("/user")
public Principal getUser(Principal principal) {
return principal;
}
@GetMapping("/tokens")
public OAuth2AccessToken getTokens(OAuth2AuthenticationToken authentication) {
return authentication.getAccessToken();
}
}
确保将 /oauth2/authorization/spring 和 http://authorization-server 等占位符替换为 OAuth 2.0 授权服务器的实际值。
此配置允许 Spring Cloud Gateway 充当 OAuth 2.0 客户端,并且 Spring Security 处理身份验证和令牌检索过程。保持无状态性,并且可以根据需要访问代币。