1

I'm developing a demo where I use OAuth2 to login using a Google account. I have the index page that redirects the user to the OAuth/Google login, and once authenticated, I want to get redirected to a page where I can display the account's name and picture. For now, I return the whole principal data, but I want to just display name and picture.

Here you can see my controller, that returns the whole principal:

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

}

What I really need is to get just some information, like name and picture from the google profile, information that is in the principal.

I can only access to the principal's name, by using .getName(), but it just returns an ID instead. I also tried getting the email like this, but it didnt work:

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

So, is it possible to get user data through that principal, or is there a better way to do it?

Flood
  • 11
  • 2

1 Answers1

-1

this would be a very long answer. Perhaps an example is helpful:

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

Vladimir
  • 612
  • 3
  • 16