我正在开发一个演示,其中我使用 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/