我想将连接到 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);
}
}
但我无法编译此代码 - 我不知道如何获取类 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
。
帮助?我不确定我哪里出了问题。
最佳答案
看起来这个页面上的答案有我的答案(感谢@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: {<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="640109050d0859091d0109050d0805000016011717240309050d084a070b09" rel="noreferrer noopener nofollow">[email protected]</a>}
关于spring-boot - 使用 Spring Boot OAuth2 针对 Google 进行身份验证时,如何将 google 用户电子邮件添加到白名单用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44138312/