By Marone: November 2020 | last update: December 2020

Keycloak custom user attributes
with preauthorize

Goal

The spring method security preauthorize as we know is powerful and it works fine with keycloak. It covers all the standard claims.

Now we want to find out how to deal with keycloak custom user attributes.

What we need

Keycloak 8.0.1
Java 11
Maven 3.x
curl 7.65
jq 1.5

Access token


As you can see the access token contains the claim customPermission

Implementing the custom methhode


The SecurityExpressionRoot implements all the default Expression Operations such as hasAuthority, hasRole,...etc.
Now we extend this class and add a new operation to handle specific permissions. the customPerm operation will check if the access token contains the claim customPermission and if it has the value which is passed from the RestController.

The custom handler


We override the createSecurityExpressionRoot operation, now we set the CustomMethodSecurityExpression.

Use the handler


This config part tells spring that we want to use all the custom stuff to be used instead of the defaults, the annotations indicates that we use global method security with pre post and Secured annotations.

Rest API


The operation custom uses @PreAuthorize annotation and requires an authenticated user with specific permission for writing . For all the incoming requests with /custom spring security will perform the CustomMethodSecurityExpression.customPerm operation.

Let's test

Because the access token contains the required information, we get the response.

References


The complete code can be found in GitHub