eugenp / tutorials

Just Announced - "Learn Spring Security OAuth":

Home Page:http://bit.ly/github-lsso

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Authorities always Returning empty in Keycloak

akashsuresh opened this issue · comments

This code always returns empty for authorities .Unable to debug.

@Bean
public GrantedAuthoritiesMapper userAuthoritiesMapperForKeycloak() {
    System.out.println("Checkpoint Y");
    return authorities -> {
        Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
        var authority = authorities.iterator().next();
        boolean isOidc = authority instanceof OidcUserAuthority;
        if (isOidc) {
            var oidcUserAuthority = (OidcUserAuthority) authority;
            var userInfo = oidcUserAuthority.getUserInfo();

            // Tokens can be configured to return roles under
            // Groups or REALM ACCESS hence have to check both
            if (userInfo.hasClaim(REALM_ACCESS_CLAIM)) {
                var realmAccess = userInfo.getClaimAsMap(REALM_ACCESS_CLAIM);
                var roles = (Collection<String>) realmAccess.get(ROLES_CLAIM);
                mappedAuthorities.addAll(generateAuthoritiesFromClaim(roles));
            } else if (userInfo.hasClaim(GROUPS)) {
                Collection<String> roles = (Collection<String>) userInfo.getClaim(GROUPS);
                mappedAuthorities.addAll(generateAuthoritiesFromClaim(roles));
            }
        } else {
            var oauth2UserAuthority = (OAuth2UserAuthority) authority;
            Map<String, Object> userAttributes = oauth2UserAuthority.getAttributes();

            if (userAttributes.containsKey(REALM_ACCESS_CLAIM)) {
                Map<String, Object> realmAccess = (Map<String, Object>) userAttributes.get(REALM_ACCESS_CLAIM);
                Collection<String> roles = (Collection<String>) realmAccess.get(ROLES_CLAIM);
                mappedAuthorities.addAll(generateAuthoritiesFromClaim(roles));
            }
        }
        return mappedAuthorities;
    };
}

The location that i have put in Checkpoint Y is the last point this code returns something.

Hey, @akashsuresh,

Please include a link to the article you're referring to so we can check it. Also, have you done any custom changes in the code?

Closed due to lack of activity