首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >@RolesAllowed注释总是在Keycloak中抛出403错误

@RolesAllowed注释总是在Keycloak中抛出403错误
EN

Stack Overflow用户
提问于 2020-08-04 15:50:00
回答 1查看 786关注 0票数 1

我是一个穿着Spring boot的新人,可能有一个愚蠢的问题。我有一个简单的spring boot rest api应用程序,带有spring安全和oauth2。Outh2 broker是Keycloak,所以我的安全过滤器如下所示

代码语言:javascript
运行
复制
@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);
    }

}

此外,我还启用了全局方法安全性

代码语言:javascript
运行
复制
@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = true, prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
}

但是当我尝试将@RolesAllowed('admin')添加到我的控制器方法中时,我总是得到403禁止错误,没有注释所有工作正常,没有令牌我得到401,如果令牌过期403。这是我的jwt示例

代码语言:javascript
运行
复制
{
  
  "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"
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-04 17:03:26

我认为这个class负责让当局。默认情况下,它在jwt中查找scopescp声明。在您的例子中,您有"scope": "profile web-origins email"。在此之后,它为每个授权添加了等于SCOPE_DEFAULT_AUTHORITY_PREFIX前缀。我认为当你从SecurityContextHolder.getContext().getAuthentication()中调试你的Authentication对象时,其 getAuthorities() 返回的权限将等于SCOPE_profileSCOPE_web-originsSCOPE_email。您应该将代码更改为:

代码语言:javascript
运行
复制
.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()

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63242356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档