@EnableResourceServer: Mapping roles

Viewed 994

How do I map roles in my resource server?

I have created what I believe to be the most simple implementation of a resource server in 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>

The app works well. I make a call to my auth server (in this case KeyCloak) and retrieve a token. I then do a http get to http://localhost:8080/user/ with the token passed in as the Authorization header.

The HTTP response contains information from the token however the authorities property is set to ROLE_USER. This does not match the roles in the token.

HTTP response

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

Token (parsed)

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

How do I extract the desired information from the token?

1 Answers

I've resolved by creating a token mapper in keycloak client. In my case the mapper has these parameters:

  • name: authorities
  • mapper type: User Realm Role
  • Token Claim Name: authorities
  • Add to access token: on
  • Add to userinfo: on

I hope this can help!

Giampiero.

Related