Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrincipalExtractor and AuthoritiesExtractor are not getting called

I have a simple OAuth2 application. I started off by creating a SecurityConfig extending WebSecurityConfigurerAdapter and annotated with @EnableOAuth2Sso. I've created an API as well in a controller to test if authentication is working. Principal gets injected into the controller and it gives the correct name.

I'm now trying to add some authorities to the principal by implementing AuthoritiesExtractor and creating it as bean. I also did the same with PrincipalExtractor to check if it is working. None of them are getting called while making any request from the browser.

Edit: This is actually doing only authentication with OIDC and hence my client and resources are on the same application.

// This is my security configuration class.

@Configuration
@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
     http
     .antMatcher("/**")
     .authorizeRequests()
       .antMatchers("/login**","/error**")
       .permitAll()
     .anyRequest()
       .authenticated();
}

@Bean
public PrincipalExtractor principalExtractor() {
    return map -> {
        System.out.println("Principal extracted.");
        User user = new User();
        user.setUsername((String)map.get("username"));
        return user;
    };
}

@Bean
public AuthoritiesExtractor authoritiesExtractor() {
    return new PrismAuthoritiesExtractor();
}
}

// And this is my AuthoritiesExtractor class defined separately just to check if doing so works.

public class PrismAuthoritiesExtractor implements AuthoritiesExtractor {

@Override
public List<GrantedAuthority> extractAuthorities(Map<String, Object> map) {
    return AuthorityUtils.commaSeparatedStringToAuthorityList("AUTH1,AUTH2");
}
}
like image 813
nikhiltejadonkana Avatar asked Apr 28 '19 20:04

nikhiltejadonkana


1 Answers

I struggled with this for a while. The reason why my AuthoritiesExtractor bean isn't called is because newer version of Spring do not use spring oauth2 autoconfigure and AuthoritiesExtractor is the oauth2 autoconfigure way to overwrite role mapping.

In current versions of spring-security you can use the delegation-based strategy with OAuth2UserService. The sample in the documentation should be enough to get you going. I'm using Kotlin, so my sample probably won't work for you.

There is also the GrantedAuthoritiesMapper which should be closer to the AuthoritiesExtractor method.

like image 117
konqi Avatar answered Nov 09 '22 16:11

konqi