Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security 5: providing roles for OAuth2 authenticated users

I have existing Spring Boot application with Spring Security 5 and OAuth2 client, I've successfully configured authentication with external OAuth2 provider (GitLab, in my case).

Now I have problem with configuring authorization. I'd like to have some method that would let me write code to resolve roles for given user (either by making a call to the database or just checking hard-coded username).

I've found out that it could be achieved by using PrincipalExtractor and AuthoritiesExtractor, described in a nice article. However, those classes are no longer present in recent Spring Security. What is an alternative way to achieve that, compatible with Spring Security 5?

like image 889
Greg Witczak Avatar asked Oct 28 '25 01:10

Greg Witczak


1 Answers

What you are looking for is called GrantedAuthoritiesMapper

it is documented here in the official spring security documentation

And here is a code example:

@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .oauth2Login(oauth2 -> oauth2
                .userInfoEndpoint(userInfo -> userInfo
                    .userAuthoritiesMapper(this.userAuthoritiesMapper())
                    ...
                )
            );
    }

    private GrantedAuthoritiesMapper userAuthoritiesMapper() {
        return (authorities) -> {
            Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

            authorities.forEach(authority -> {
                if (OidcUserAuthority.class.isInstance(authority)) {
                    OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority;

                    OidcIdToken idToken = oidcUserAuthority.getIdToken();
                    OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();

                    // Map the claims found in idToken and/or userInfo
                    // to one or more GrantedAuthority's and add it to mappedAuthorities

                } else if (OAuth2UserAuthority.class.isInstance(authority)) {
                    OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority;

                    Map<String, Object> userAttributes = oauth2UserAuthority.getAttributes();

                    // Map the attributes found in userAttributes
                    // to one or more GrantedAuthority's and add it to mappedAuthorities

                }
            });

            return mappedAuthorities;
        };
    }
}

There are several more examples and explanations in the spring security documentation.

like image 197
Toerktumlare Avatar answered Oct 30 '25 21:10

Toerktumlare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!