Our application is now secured, but it would be nice if we could show some information on the logged on user.
To do that, have Spring inject an org.springframework.security.oauth2.core.user.OAuth2User
instance into the controller method like this:
@Controller
@RequestMapping("/")
public class HomeController {
@GetMapping
public String home(Model model,
@AuthenticationPrincipal OAuth2User user) {
String name = user.getAttribute("name");
String email = user.getAttribute("email");
model.addAttribute("name", name);
model.addAttribute("email", email);
return "index";
}
}
To make the injection work, we need to annotate the parameter with org.springframework.security.core.annotation.AuthenticationPrincipal
.
Using the user object, we can retrieve information about the logged on user.
In this example, we retrieve the name of the user and his or her email address.
We put those as attributes in the Model
so we can display them in our Thymeleaf template:
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Google login demo</title>
</head>
<body>
<div>Hello <span th:text="|${name} (${email})|"></span></div>
</body>
</html>
Restart the application and refresh the browser.
The name and email address of the user is now shown: