@EnableResourceServer:映射角色

@EnableResourceServer: Mapping roles

如何在我的资源服务器中映射角色?

我在 Spring Boot:

中创建了我认为最简单的资源服务器实现

Application.java

@SpringBootApplication
@RestController
@EnableResourceServer
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @RequestMapping(value = "/user")
    public Principal user(Principal principal) {
        return principal;
    }
}

application.properties

security.oauth2.resource.user-info-uri=myUserInfoUri
security.oauth2.client.client-id=myId
security.oauth2.client.client-secret=mySecret

pom.xml

...
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
    </dependency>
</dependencies>

该应用运行良好。我调用我的身份验证服务器(在本例中为 KeyCloak)并检索令牌。然后我使用作为授权 header.

传入的令牌访问 http://localhost:8080/user/

HTTP 响应包含来自令牌的信息,但是 authorities 属性 设置为 ROLE_USER。这与令牌中的角色不匹配。

HTTP 响应

...
"userAuthentication": {
  "authorities": [
    {
      "authority": "ROLE_USER"
    }
  ],
  "details": {
    "sub": "93f566bd-df68-4c68-b3c6-0173c476bc02",
    "name": "Andrew Neeson",
    "preferred_username": "andy",
    "given_name": "Andrew",
    "family_name": "Neeson",
  ...

令牌(已解析)

...
"realm_access": {
  "roles": [
    "role_1",
    "role_2"
  ]
},
"resource_access": {
  "account": {
    "roles": [
      "manage-account",
      "view-profile"
    ]
  }
},
"name": "Andrew Neeson",
"preferred_username": "andy",
"given_name": "Andrew",
"family_name": "Neeson",
...

如何从令牌中提取所需信息?

我已经通过在 keycloak 客户端中创建令牌映射器解决了这个问题。 在我的例子中,映射器有这些参数:

  • 姓名:当局
  • 映射器类型:用户领域角色
  • 令牌声明名称:authorities
  • 添加到访问令牌:on
  • 添加到用户信息:开

希望对您有所帮助!

詹皮耶罗。