Spring Security Oauth oauth2UserService(works on github but doesn't work on google)

4.7k views Asked by At

I am learning tutorial https://spring.io/guides/tutorials/spring-boot-oauth2/ in the last example there is an example of adding error message. Everything seems work fine but i don't understand why when i login with github this bean works but when i login with google it doesn't work.(When i debug it breakpoint stops on github login and doesn't stop when login via google). Where is noticed that is only for github? bean(fully from example):

@Bean
public OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService(WebClient rest) {
    DefaultOAuth2UserService delegate = new DefaultOAuth2UserService();// breakpoint here
    return request -> {
        OAuth2User user = delegate.loadUser(request); //and breakpoint here
        if (!"github".equals(request.getClientRegistration().getRegistrationId())) {
            return user;
        }

        OAuth2AuthorizedClient client = new OAuth2AuthorizedClient
                (request.getClientRegistration(), user.getName(), request.getAccessToken());
        String url = user.getAttribute("organizations_url");
        List<Map<String, Object>> orgs = rest
                .get().uri(url)
                .attributes(oauth2AuthorizedClient(client))
                .retrieve()
                .bodyToMono(List.class)
                .block();

        if (orgs.stream().anyMatch(org -> "spring-projects".equals(org.get("login")))) {
            return user;
        }

        throw new OAuth2AuthenticationException(new OAuth2Error("invalid_token", "Not in Spring Team", ""));
    };
}
2

There are 2 answers

1
khseok On

You can use OidcUserService to hook google oauth authentication process.

Check the article below.

https://www.devglan.com/spring-security/spring-boot-security-google-oauth

wish this helps..

0
Jose Amadeo Diaz Diaz On

Sultan Zhumatayev, for google, you must implement:

@Bean
public OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
    final OidcUserService delegate = new OidcUserService();
    return (userRequest) -> {
        // Delegate to the default implementation for loading a user
        OidcUser oidcUser = delegate.loadUser(userRequest);

        //OAuth2AccessToken accessToken = userRequest.getAccessToken();
        //Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

        // TODO
        // 1) Fetch the authority information from the protected resource using accessToken
        // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities

        // 3) Create a copy of oidcUser but use the mappedAuthorities instead
        //oidcUser = new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo());

        return oidcUser;
    };
}