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

时间:2017-05-23 14:55:08

标签: spring-boot spring-security-oauth2 google-oauth2

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

我基于Spring Tutorial创建了一个Spring Boot OAuth2应用程序

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

我正在对Google进行身份验证(已成功)。我想确定用户的电子邮件地址,以便我可以对用户进行身份验证。

本网站

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

建议我可以解压缩我从谷歌回来的“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);
        }
}

但是我无法编译这段代码 - 我无法弄清楚如何获取类 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

帮助?我不确定我哪里出错了。

1 个答案:

答案 0 :(得分:1)

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

How to get custom user info from OAuth2 authorization server /user endpoint

以下是代码:

    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$$91415b85 :
details map is: {email=myemailaddress@gmail.com}