By Marone: November 2020 | last update: December 2020
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 needKeycloak 8.0.1
As you can see the access token contains the claim customPermission
Implementing the custom methhode
SecurityExpressionRootimplements 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
customPermissionand if it has the value which is passed from the RestController.
The custom handler
We override the
createSecurityExpressionRootoperation, 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
customuses @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 testBecause the access token contains the required information, we get the response.
- Setup keycloak with user
- How to get Access token
- Custom attributes in keycloak
- Spring method Security with Keycloak
The complete code can be found in GitHub