Muhammed Caylak
Muhammed Caylak

Reputation: 353

Spring boot keycloak integration comes in role null in @preauthorize

I am trying to perform authorization operations using keycloak.

My security config class works fine, I successfully create authentication via jwt token and perform the necessary role mapping. This is clearly visible through the security context holder.

enter image description here

I'm using the preauthorize annotation, because the authorities are null in it, authorization is not provided, I get 403.

enter image description here

I still don't understand how it is possible, can you help?

Upvotes: 0

Views: 1322

Answers (1)

Muhammed Caylak
Muhammed Caylak

Reputation: 353

After a long struggle, I found the solution.

@Override
protected KeycloakAuthenticationProvider keycloakAuthenticationProvider() {
    return new KeycloakAuthenticationProvider() {

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) authentication;
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

            for (String role : ((KeycloakPrincipal) token.getPrincipal()).getKeycloakSecurityContext().getToken().getRealmAccess().getRoles()) {
                grantedAuthorities.add(new KeycloakRole(role));
            }

            return new KeycloakAuthenticationToken(token.getAccount(), token.isInteractive(), new SimpleAuthorityMapper().mapAuthorities(grantedAuthorities));
        }

    };
}

We can reach the solution by setting the roles into KeycloakAuthenticationToken with the following method in the Security config class.

Upvotes: 2

Related Questions