java - Spring Security - 使用主体登录 OAuth/Google 后如何检索数据(如电子邮件、姓名、图片等)?

标签 java spring-boot spring-security spring-security-oauth2

我正在开发一个演示,其中我使用 OAuth2 使用 Google 帐户登录。我有将用户重定向到 OAuth/Google 登录的索引页面,经过身份验证后,我想重定向到可以显示帐户名称和图片的页面。现在,我返回全部主要数据,但我只想显示名称和图片。

在这里您可以看到我的 Controller ,它返回整个主体:

import java.security.Principal;

import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class Controller {

    //returns the index page
    @GetMapping("/")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index.html");
        return modelAndView;
    }

    //after login, redirects to this page, with user details
    @RequestMapping(value="/user")
    public Principal user(Principal principal) {

        return principal;
    }

}

我真正需要的是获取一些信息,例如 Google 个人资料中的姓名和图片,以及主体中的信息。

我只能使用 .getName() 访问主体的名称,但它只返回一个 ID。 我也尝试过这样获取电子邮件,但没有成功:

@RequestMapping(value="/user")
public Authentication user(OAuth2Authentication authentication) {
        LinkedHashMap<String, Authentication> details = (LinkedHashMap<String, Authentication>) authentication.getUserAuthentication().getDetails();
        return details.get("email");
    }

那么,是否可以通过该主体获取用户数据,或者是否有更好的方法来实现?

最佳答案

这将是一个很长的答案。也许一个例子会有所帮助:

https://github.com/Grauzone/spring-boot-react-oauth2-social-login-demo

关于java - Spring Security - 使用主体登录 OAuth/Google 后如何检索数据(如电子邮件、姓名、图片等)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61777809/

相关文章:

java - 未找到 Android Studio 注释抽象处理器

java - SpringBoot 2 元素未绑定(bind)

java - 如何修复Java异常 "SQLSyntaxErrorException: Table ' x.y'不存在”

java.sql.SQLException 找不到合适的驱动程序,但可以在 Netbeans 中完美连接

java - permgen 是否包含在 -Xmx 中?

java - 基本 Spring-Security MVC 应用程序中的 404 错误

java - 当发生超时后调用Servlet方法( Controller )时,Spring Security 3.1重定向到登录不起作用

java - 为什么/login?logout 会重定向到/login?

java - Java 中链表的递归最大值

ios - 在 OS X 中设置 spring.profiles.active