I am using Keycloak
in my REST
application with spring-boot
.
It works correctly, I have defined roles
in Keycloak
, then in my Config.class I allow access to the end-points that interest me according to the role of each user. I have the problem when trying to retrieve the user information in my back (name, principal, authorities...).
I have read various SO
POSTS like these:
Does anyone know why I get null when trying to access SecurityContext
?
My goal is to retrieve user data
CodePudding user response:
You are initializing the securityContext object in your controller when the controller is first created:
private SecurityContext securityContext = SecurityContextHolder.getContext();
At that time, there is no security context available, meaning that the context is always null.
Don't use a private variable in a controller to store the context, instead, fetch it from the SecurityContextHolder
in the getLicenses
method:
@GetMapping(value = "/getLicenses")
public ResponseEntity<List<License>> getLicenses() {
SecurityContext securityContext = SecurityContextHolder.getContext();
System.out.println("SecurityContext: " securityContext);
System.out.println("Authentication securityContext: " securityContext.getAuthentication());
return new ResponseEntity<List<License>>(licenseService.getLicenses(), null, HttpStatus.OK);
}