Rahul
Rahul

Reputation: 1005

How to give client role based access in keycloak spring adapter?

I have realm based roles and client-based roles. In my keycloak realm. Take for example real role Teenager and client role Student.

Now I want to allow certain routes in my spring app based on client role student.

keycloak.security-constraints[1].authRoles[0]=Teenager
keycloak.security-constraints[1].securityCollections[0].patterns[0]=/teen

I understand with this configuration teen route would be allowed only for roles "Teenager"

Now for a route /teen/student

keycloak.security-constraints[1].authRoles[0]=Student
keycloak.security-constraints[1].securityCollections[0].patterns[0]=/teen/student

can I do in the above manner or I need to chain some other key after .authRoles[0]

I have added this keycloak.use-resource-role-mappings=true in my properties file.

Upvotes: 1

Views: 2979

Answers (1)

dreamcrash
dreamcrash

Reputation: 51443

First, you need to add the constrains in different array positions:

keycloak.security-constraints[0].authRoles[0]=Teenager
keycloak.security-constraints[0].securityCollections[0].patterns[0]=/teen

keycloak.security-constraints[1].authRoles[0]=Student
keycloak.security-constraints[1].securityCollections[0].patterns[0]=/teen/student

But this still does not work because you cannot mix constraints that use realm-roles and client.roles in the properties file. According to the Keycloak documentation:

If set to true, the adapter will look inside the token for application level role mappings for the user. If false, it will look at the realm level for user role mappings. This is OPTIONAL. The default value is false.

So it either works for the client-level or the realm-level. You will have to do it via code.

You add the client-roles constraints into your properties file, like:

keycloak.security-constraints[0].authRoles[0]=Student
keycloak.security-constraints[0].securityCollections[0].patterns[0]=/teen/student

keycloak.use-resource-role-mappings=true

, and you deal with the realm-roles in the code:

@Override
protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);
    http.authorizeRequests()
            .antMatchers("/teen")
            .hasRole("Teenager")
            .anyRequest()
            .authenticated();
    ...
}

You might want to have a look into this thread of the keycloak group.

Upvotes: 1

Related Questions