Keycloak不定义用户角色

Keycloak does not define user roles

提问人:asayke 提问时间:10/26/2023 更新时间:10/26/2023 访问量:20

问:

我为 Spring Boot 3 编写了一个小配置和一个简单的控制器:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf(t -> t.disable());
        http.addFilterAfter(createPolicyEnforcerFilter(), BearerTokenAuthenticationFilter.class);

        http.sessionManagement(t -> t.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        return http.build();
    }

    private ServletPolicyEnforcerFilter createPolicyEnforcerFilter() {
        return new ServletPolicyEnforcerFilter(new ConfigurationResolver() {
            @Override
            public PolicyEnforcerConfig resolve(HttpRequest request) {
                try {
                    return JsonSerialization.readValue(getClass().getResourceAsStream("/policy-enforcer.json"), PolicyEnforcerConfig.class);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
}
{
  "realm": "hostel",
  "auth-server-url": "http://localhost:8080",
  "resource": "hostel-client",
  "credentials": {
    "secret": "B65bBs1DIzjEvqdHH86n9xj2QjjSWcYa"
  },
  "http-method-as-scope": true,
  "paths" : [
    {
      "path": "/swagger-ui/*",
      "enforcement-mode": "DISABLED"
    },{
      "path": "/v3/api-docs/*",
      "enforcement-mode": "DISABLED"
    },{
      "path": "/public/*",
      "enforcement-mode": "DISABLED"
    }
  ]
}
@RestController
@RequestMapping("/user")
@SecurityRequirement(name = "Keycloak")
public class UserController {
    @GetMapping
    public String message() {
        return "user access";
    }
}

我已经添加了 Realm 角色、配置了用户资源、用户策略和用户权限,但是当我使用角色为“user”的用户的令牌请求 /user/* 时,我得到了 403

用户资源

用户政策

用户权限

我还链接了客户端角色和领域角色,但这没有帮助

以下是我的令牌包含的内容:

{
  "exp": 1698251063,
  "iat": 1698250763,
  "jti": "452188e1-61e1-4577-8049-33106abcfa6c",
  "iss": "http://localhost:8080/realms/hostel",
  "aud": "account",
  "sub": "d6703dd1-edcb-4b04-bc11-0cd5a1cf407d",
  "typ": "Bearer",
  "azp": "hostel-client",
  "session_state": "d475bb03-590c-4fa9-b093-1faa47258ee8",
  "acr": "1",
  "allowed-origins": [
    "*"
  ],
  "realm_access": {
    "roles": [
      "default-roles-hostel",
      "offline_access",
      "uma_authorization",
      "user"
    ]
  },
  "resource_access": {
    "hostel-client": {
      "roles": [
        "user"
      ]
    },
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    }
  },
  "scope": "profile email roles",
  "sid": "d475bb03-590c-4fa9-b093-1faa47258ee8",
  "email_verified": false,
  "name": "someone someone",
  "preferred_username": "someone",
  "given_name": "someone",
  "family_name": "someone",
  "email": "[email protected]"
}
Java Spring-Boot 安全 JWT Keycloak

评论


答: 暂无答案