【发布时间】:2023-03-26 16:06:01
【问题描述】:
根据标题,我正在像这样设置 webflux 配置
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class WebSecurityConfig {
String jwkSetUri = "http://localhost:8080/auth/realms/demo/protocol/openid-connect/certs";
@Bean
public ReactiveJwtDecoder jwtDecoder() {
return
ReactiveJwtDecoders.fromIssuerLocation("http://localhost:8080/auth/realms/demo");
}
@Bean
public SecurityWebFilterChain configure(ServerHttpSecurity http) {
http.authorizeExchange()
.oauth2Login()
.and()
.
...
.oauth2ResourceServer()
.jwt()
.jwkSetUri(jwkSetUri)
// .jwtDecoder(jwtDecoder())
.jwtAuthenticationConverter(grantedAuthoritiesExtractor());
return http.build();
}
@Bean
Converter<Jwt, Mono<AbstractAuthenticationToken>> grantedAuthoritiesExtractor() {
GrantedAuthoritiesExtractor extractor = new GrantedAuthoritiesExtractor();
return new ReactiveJwtAuthenticationConverterAdapter(extractor);
}
static class GrantedAuthoritiesExtractor
extends JwtAuthenticationConverter {
public Collection<GrantedAuthority> extractAuthorities(Jwt jwt) {
Collection<?> authorities = (Collection<?>)
jwt.getClaims().getOrDefault("roles", Collections.emptyList());
return authorities.stream()
.map(Object::toString)
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
}
使用以下 application.yml
security:
oauth2:
client:
provider:
keycloak-local:
issuer-uri: http://localhost:8080/auth/realms/demo
registration:
keycloak-local:
client-id: some-id
client-secret: ...
resourceserver:
jwt:
issuer-uri: http://localhost:8080/auth/realms/demo
jwk-set-uri: http://localhost:8080/auth/realms/demo/protocol/openid-
connect/certs
token格式是这样的
"realm_access": {
"roles": [
"offline_access",
"uma_authorization"
]
},
"resource_access": {
"someclient": {
"roles": [
"uma_protection"
]
},
"account": {
"roles": [
"manage-account",
"manage-account-links",
"view-profile"
]
}
},
"scope": "profile email ",
"organizationId": "605b74813bd72c65a24a1704",
"accountId": "605b74813bd72c65a24a1709",
"email_verified": false,
"roles": [
"ROLE_ADMIN"
],
"preferred_username": "someUsername",
"userId": "605b74813bd72c65a24a1706",
"email": "email.com"
}`
当然,“角色”数组是我最希望访问的数组(是我在数据库中定义的角色)。
在设置之后似乎什么都没有改变。 所以在我的控制器中,我尝试使用 @Preauthorize 注释以访问某些方法,但它继续使用范围声明。
@PreAuthorize("hasAuthority('SCOPE_email')")
有人知道我错过了什么吗?请注意,我参考了官方文档,也参考了this tutorial。 对于 webflux。
谢谢
【问题讨论】:
标签: java spring-security keycloak spring-webflux spring-security-oauth2