[JAVA] How to give Spring Security authenticated user information other than userId and password and how to refer to it

Overview

In my memo, the tutorial related to Spring Security, it is said that the userId and password used for authentication can be referenced from the session, but I just wondered about any other parameters. Nothing happened, all I had to do was add a getter to the class that implemented UserDetails. ..

Simple class example


public class User {
    private String userId;
    private String password;
    private String hoge;
    //getter,setter omitted
}

public class UserDetailsImpl implements UserDetails {

    private final User user;
    
    public UserDetailsImpl(User user) {
        this.user = user;
    }

    public String getHoge() {
        return user.getHoge();
    }
    //Method to be overrided omitted
}

See the article I wrote earlier for the authentication method I implemented DB login authentication processing with Spring Security (using MyBatis) I implemented DB login authentication processing with Spring Security (using MyBatis) Part 2

A method of accessing the user information stored in the session with the controller after the user is authenticated as described above. Use Authentication Principal annotation

@Controller
public class Controller {
    
    @RequestMapping("/")
    public index(@AuthenticationPrincipal UserDetailsImpl userDetails) {
        System.out.println(userDetails.getUserId) // userId
        System.out.println(userDetails.getPassword) //password
        System.out.println(userDetails.getHoge) //hoge
    }

Bonus, how to refer from Thymeleaf

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"> <!--Add this and use Spring Security from Thymeleaf-->

<!--abridgement-->
<body>
  <h>Hello,<span sec:authentication="principal.userId"></span>Mr.</h> <!-- principal.Can be referenced by member variable name-->
</body>




Recommended Posts

How to give Spring Security authenticated user information other than userId and password and how to refer to it
It was surprisingly easy. How to update user information without entering a password
How to implement authentication process by specifying user name and password in Spring Boot
[Android 9.0 Pie] Example of how to call strings.xml other than Activity and Fragment
[Spring Boot] How to refer to the property file