使用 Spring Boot OAuth2 针对 Google 进行身份验证时如何将 google 用户电子邮件发送到白名单用户

How to get google user email to whitelist users when authenticating using Spring Boot OAuth2 against Google

我想将连接到我的 OAuth2 客户端的用户列入白名单,但我不知道如何获取用户名(特别是 Google 电子邮件地址)。

我根据 Spring 教程

创建了一个 Spring Boot OAuth2 应用程序

https://spring.io/guides/tutorials/spring-boot-oauth2/#_social_login_manual

我正在针对 Google 进行身份验证(成功)。我想确定用户电子邮件地址,以便我可以将身份验证用户列入白名单。

这个网站,

http://www.baeldung.com/spring-security-openid-connect#filter

建议我可以解压我从 Google 回来的 "id_token",像这样:

/**
 * logic to unpack a ConnectID id_token like what we get from Google -
 * see "Spring Security and OpenID Connect" - heading '4. Custom OpenID Connect Filter':
 *         http://www.baeldung.com/spring-security-openid-connect#filter
 * 
 * @param oa2token
 * @return
 */
private static UsernamePasswordAuthenticationToken getOpenIDDataForToken(OAuth2AccessToken oa2token)
{
        try {
            String idToken = oa2token.getAdditionalInformation().get("id_token").toString();
            Jwt tokenDecoded = JwtHelper.decode(idToken);
            Map<String, String> authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class);

            OpenIdConnectUserDetails user = new OpenIdConnectUserDetails(authInfo, oa2token);
            return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        } catch (InvalidTokenException e) {
            throw new BadCredentialsException("Could not obtain user details from token", e);
        }
}

但我无法编译此代码 - 我不知道如何获得 class JtwHelper!

我搜索了一下,以下可能是正确的 Maven 依赖项:

        <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-jwt -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-jwt</artifactId>
        </dependency>

但是将它添加到我的 pom.xml 没有帮助 - 我没有在我的 .m2 存储库中得到一个真正的 Jar 文件 - 我得到一个文本文件!!!最重要的是,Eclipse 不解析类型 JwtHelper.

求助?我不知道哪里错了。

看起来这个 SO 页面上的答案有 my 答案(感谢 @user2802927):

代码如下:

    Principal principal = servlet_request.getUserPrincipal();
    try {
         if (principal != null) {
                OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
                Authentication authentication = oAuth2Authentication.getUserAuthentication();
                Map<String, String> details = new LinkedHashMap<>();
                details = (Map<String, String>) authentication.getDetails();
                Map<String, String> map = new LinkedHashMap<>();
                map.put("email", details.get("email"));
                logger.debug("details map is: {}", map);
            }
    } catch (Exception e) {
        logger.error("dumping principal " + principal + "failed, exception: ", e );
    }

输出显示我找到了成功-用户的电子邮件地址!!!

2017-05-23 11:48:26.751 DEBUG 7687 --- [nio-8443-exec-1] ication$$EnhancerBySpringCGLIB$415b85 :
details map is: {email=myemailaddress@gmail.com}