Spring Security Oauth oauth2UserService(在github上工作,但在google上不工作)

omjgkv6w  于 12个月前  发布在  Spring
关注(0)|答案(2)|浏览(196)

我正在学习教程https://spring.io/guides/tutorials/spring-boot-oauth2/在最后一个例子中有一个添加错误消息的例子。一切似乎都很好,但我不明白为什么当我用github登录时,这个bean工作,但当我用google登录时,它不工作。(当我调试它时,断点停止在github登录时,通过google登录时不会停止)。注意到这只适用于github?bean(完全来自例子):

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

字符串

6vl6ewon

6vl6ewon1#

你可以使用OidcUserService来挂接google oauth认证过程。
检查下面的文章。
https://www.devglan.com/spring-security/spring-boot-security-google-oauth
希望这对你有帮助。

wbgh16ku

wbgh16ku2#

苏丹朱马塔耶夫,对于谷歌,你必须实现:

@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;
    };
}

字符串

相关问题