Spring Authorization Server入门 Spring Cloud Gateway对接认证服务
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain springSecurityWebFilterChain(ServerHttpSecurity http) {
http
// ... 其他配置 ...
.authorizeExchange(exchanges ->
exchanges
.anyExchange().access(authorizeExchangeSpec ->
authorizeExchangeSpec
.requestMatchers(EndpointRequest.to("login", "oauth2-redirect")).permitAll()
.anyExchange().access(new AuthorizationManager())
)
)
// ... 其他配置 ...
;
return http.build();
}
@Bean
public ReactiveJwtDecoder jwtDecoder(ReactiveOAuth2AuthorizedClientService clientService) {
return JwtDecoders.fromOidcIssuerLocation(issuerUri);
}
}
public class AuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {
private final ReactiveOAuth2AuthorizedClientService clientService;
public AuthorizationManager(ReactiveOAuth2AuthorizedClientService clientService) {
this.clientService = clientService;
}
@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext context) {
return authentication
.flatMap(auth -> clientService.loadAuthorizedClient(
auth.getName(),
clientRegistrationId,
(OAuth2AuthorizedClient authorizedClient) -> context.getExchange()
.getRequest()
.mutate()
.header(HttpHeaders.AUTHORIZATION, "Bearer " + authorizedClient.getAccessToken().getTokenValue())
.build()
))
.map(authorizedClient -> new AuthorizationDecision(true))
.onErrorReturn(new AuthorizationDecision(false));
}
}
在这个代码实例中,我们定义了一个SecurityConfig
类,它使用Spring Security的WebFlux配置了Spring Cloud Gateway的安全性。我们创建了一个ServerHttpSecurity
的实例,并通过authorizeExchange
方法配置了路由的权限。我们还定义了一个AuthorizationManager
类,它使用ReactiveOAuth2AuthorizedClientService
来检查用户是否有权访问特定的路由。如果用户已经被授权,则原始请求会被修改,添加了一个包含访问令牌的Authorization
头部。
评论已关闭