I have a REST API springboot application that uses keycloack as authentication. All work fine with authentication and autorization.
Now I have to schedule some jobs that will have to use resource services. The execution of these services is bound by the fact that there is an authenticated keycloack user and that he has an 'admin' role.
This is how I check if user is authorized:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
KeycloakPrincipal<?> userDetails = (KeycloakPrincipal<?>) authentication.getPrincipal();
AccessToken accessToken = userDetails.getKeycloakSecurityContext().getToken();
AccessToken.Access resourceAccess = accessToken.getResourceAccess(env.getProperty("keycloak.resource"));
roles = resourceAccess.getRoles();
boolean isAuthorized = userRoles.contains('admin')
How can I set my admin user in the SecurityContextHolder?