我是一个穿着Spring boot的新人,可能有一个愚蠢的问题。我有一个简单的spring boot rest api应用程序,带有spring安全和oauth2。Outh2 broker是Keycloak,所以我的安全过滤器如下所示
@Configuration
@EnableWebSecurity
public class WebSecurityAdditionalConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.authorizeRequests()
.antMatchers("/api/**")
.authenticated()
.and()
.oauth2ResourceServer().jwt();
http.csrf().disable().sessionManagement().sessionCreationPolicy(
SessionCreationPolicy.STATELESS);
}
}
此外,我还启用了全局方法安全性
@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = true, prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
}
但是当我尝试将@RolesAllowed('admin')添加到我的控制器方法中时,我总是得到403禁止错误,没有注释所有工作正常,没有令牌我得到401,如果令牌过期403。这是我的jwt示例
{
"realm_access": {
"roles": [
"admin"
]
},
"resource_access": {
"edge_client": {
"roles": [
"cli_admin"
]
}
},
"scope": "profile web-origins email",
"email_verified": false,
"name": "John Spartan",
"groups": [
"admin"
],
"preferred_username": "test_admin",
"given_name": "John",
"family_name": "Spartan"
}
发布于 2020-08-04 17:03:26
我认为这个class负责让当局。默认情况下,它在jwt
中查找scope
或scp
声明。在您的例子中,您有"scope": "profile web-origins email"
。在此之后,它为每个授权添加了等于SCOPE_
的DEFAULT_AUTHORITY_PREFIX
前缀。我认为当你从SecurityContextHolder.getContext().getAuthentication()
中调试你的Authentication
对象时,其 getAuthorities()
返回的权限将等于SCOPE_profile
,SCOPE_web-origins
和SCOPE_email
。您应该将代码更改为:
.oauth2ResourceServer()
.jwt(customizer -> {
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
//write your own Converter<Jwt, Collection<GrantedAuthority>> jwtGrantedAuthoritiesConverter
//and override Collection<GrantedAuthority> convert(Jwt jwt) to get roles from
//realm_access.roles
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
customizer.jwtAuthenticationConverter(jwtAuthenticationConverter)
})
或者使用Keycloak Adapter for Spring而不是oauth2ResourceServer()
https://stackoverflow.com/questions/63242356
复制相似问题