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

问题描述 投票:0回答:1

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

在这里您可以看到我的控制器,该控制器返回整个主体:

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

因此,是否有可能通过该主体获取用户数据,或者有更好的方法呢?

java spring-boot spring-security spring-security-oauth2
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.