【问题标题】:@EnableResourceServer: Mapping roles@EnableResourceServer:映射角色
【发布时间】:2018-05-10 14:24:42
【问题描述】:

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

我在 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)并检索令牌。然后,我使用作为 Authorization 标头传入的令牌对 http://localhost:8080/user/ 进行 http 获取。

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",
...

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

【问题讨论】:

    标签: spring-security jwt spring-security-oauth2


    【解决方案1】:

    我已通过在 keycloak 客户端中创建令牌映射器来解决。 就我而言,映射器具有以下参数:

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

    希望对你有帮助!

    詹皮耶罗。

    【讨论】:

    • 你能发布一个sn-p的代码吗?我有一个可行的解决方案并忘记发布它,但是鉴于您首先回答了,我给您一个正确答案的机会是公平的!如果没有,我会在一周内发布解决方案。
    • @andy-n 我没有任何代码,只是在 keycloak 管理控制台中编辑了客户端。
    • 啊。好的 - 抱歉错过了重点。因为 JWT 令牌上的属性是“权限”,所以 Spring Boot 会自动选择它。好答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 2020-10-18
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多