Using spring security annotations with keycloak

I'm just a beginner in Spring Security, but I would like to know if keycloak can be configured in such a way that I can use @PreAuthorize , @PostAuthorize , @Secured and other annotations. For example, I configured keycloak-spring-security-adapter and Spring Security in my simple Spring Rest webapp, so that I have access to the Principal object in my controller, for example:

 @RestController public class TMSRestController { @RequestMapping("/greeting") public Greeting greeting(Principal principal, @RequestParam(value="name") String name) { return new Greeting(String.format(template, name)); } ... } 

But when I try this (just an example, actually I want to execute a custom EL expression before authorization):

 @RestController public class TMSRestController { @RequestMapping("/greeting") @PreAuthorize("hasRole('ADMIN')") public Greeting greeting(Principal principal, @RequestParam(value="name") String name) { return new Greeting(String.format(template, name)); } ... } 

I get an exception:

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: authentication object not found in SecurityContext

In my Spring security config, I have enabled global method protection:

What do I need to make these Spring Security Annotations work? Can this annotation be used at all in this context?

+5
source share
1 answer

You still need to configure Spring Security with Keycloak. Take a look at the adapter documentation for annotation-based customization. Once configured, Spring Security Annotations will work with authorized calls.

+3
source

Source: https://habr.com/ru/post/1239600/


All Articles