PrincipalExtractor and AuthoritiesExtractor are not getting called

£可爱£侵袭症+ 提交于 2020-01-04 11:08:10

问题


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");
}
}

回答1:


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.



来源:https://stackoverflow.com/questions/55894402/principalextractor-and-authoritiesextractor-are-not-getting-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!