Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my oauth2 config not using my custom UserService?

I'm trying to use authentication by google. I am using springboot2, so most of the configuration is automatic. The authentication itself works good, but afterwards I would like to populate Principal with my own data (roles, username, and stuff).

I've created MyUserService that exteds DefaultOauth2UserService, and I am trying to use it as follows:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    MyUserService myUserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .oauth2Login()
                .userInfoEndpoint()
                    .userService(myUserService);
    }
}

I've checked with debuger, that application never actually uses loadUser methods. And here is implementation of MyUserService:

@Component
public class MyUserService extends DefaultOAuth2UserService {
    @Autowired
    UserRepository userRepository;

    public MyUserService(){
        LoggerFactory.getLogger(MyUserService.class).info("initializing user service");
    }

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        OAuth2User oAuth2User = super.loadUser(userRequest);
        Map<String, Object> attributes = oAuth2User.getAttributes();

        String emailFromGoogle = (String) attributes.get("email");
        User user = userRepository.findByEmail(emailFromGoogle);
        attributes.put("given_name", user.getFirstName());
        attributes.put("family_name", user.getLastName());

        Set<GrantedAuthority> authoritySet = new HashSet<>(oAuth2User.getAuthorities());

        return new DefaultOAuth2User(authoritySet, attributes, "sub");
    }
}
like image 694
Maciej Kubiak Avatar asked Apr 08 '18 08:04

Maciej Kubiak


2 Answers

Actually the solution was just to add another property for google authentication:

spring.security.oauth2.client.registration.google.scope=profile email

Not sure, what is the default scope, and why entrance to the service is dependent on scope, but without this line the code never reached my custom service.

like image 91
Maciej Kubiak Avatar answered Oct 30 '22 17:10

Maciej Kubiak


I think you're missing the @EnableOAuth2Client annotation at the top of your SecurityConfig class.

Regardless, I made an examplewith a Custom user service for oauth2 here https://github.com/TwinProduction/spring-security-oauth2-client-example/ if it helps

like image 20
TwiN Avatar answered Oct 30 '22 19:10

TwiN