[JAVA] I want to get the information of the class that inherits the UserDetails class of the user who is logged in with Spring Boot.

environment

Spring Boot 2.4.0 java 1.8 thymeleaf 3.0.11 Spring Security 2.4.0

What you want to achieve

I want to get the information of the class that inherits USERDETAILS of the logged-in user.

I tried various things and managed to realize

It took almost a whole day. I don't think I understand Spring Boot properly, but I've looked at various sites and tried it, and it worked, so I'll keep a record of it.

Classes that inherit from USERDETAILS

Tenants class
Staff class

Login authentication

The loadUserByUsername method of the MyUserDetailsService class separates the returned classes.

MyUserDetailsService class


public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//Throw an exception if the argument is null
    if (Objects.isNull(username)) {
      throw new UsernameNotFoundException("username is empty");
	  }
    Tenants tenants = tenantRepository.findByAdminId(username);
    Staff staff = staffRepository.findByEmail(username);
    //Throw an exception if null is returned
    if(tenants != null) {
    	return tenants;
    } else if(staff != null) {
    	return staff;
    } else {
    	throw new UsernameNotFoundException("Not found username: " + username);
    }

	}

controller

I want to display which class is currently logged in with the controller that displays the top screen after login.

As a result of various trials, it is now possible to get which class is authenticated with the implementation below.

@GetMapping("/top")
public ModelAndView userTop(eModelAndView mv, Principal principal) {
	
        //Get a class that inherits USERDETAILS of the logged-in user
	Authentication auth = (Authentication) principal;
	String authClass = auth.getPrincipal().getClass().getSimpleName();
	if(authClass.equals("Tenants")) {
		System.out.println("It's a tenant class! !!");
		String tenantId = ((Tenants)auth.getPrincipal()).getId().toString();
		httpServletResponse.addCookie(new Cookie("tenantId", tenantId));
	}
	if(authClass.equals("Staff")) {
		System.out.println("Staff class! !!");
		String tenantId = ((Staff)auth.getPrincipal()).getTenantId().toString();
		httpServletResponse.addCookie(new Cookie("tenantId", tenantId));
	}
}

Where I was addicted

I don't know how to use Principal or Authentication, ・ How to pass arguments ・ How to use @AuthenticationPrincipal annotation ・ Do you need a cast? ・ I have a Tenants class in the Principal, but I can't retrieve the field? -GetClass () appears in the code assistant, but I get an error and can't execute it? etc. .. ..

Apparently, Principal contains all the records of the class that inherited UserDetails when the authentication was successful.

However, only username can be retrieved. .. ..

I just thought I should use Principal, but apparently it wasn't.

It was an image that the Principal class was included in the Authentication class and the UserDetails class was included in the Principal. (I don't know if it fits)

Just with that image

//First get Authentication from the Principal passed to the controller argument
Authentication auth = (Authentication) principal;
String authClass = auth.getPrincipal() //Get Principal
   .getClass() //Get class
   .getSimpleName(); //Exclude package name

This flow worked.

the first Do I need to cast to Principal → Authentication? ?? I felt like, but it didn't work unless I did this.

How to display in view with thymeleaf

<div sec:authentication="principal"></div>
<div th:text="${#authentication.principal}"></div>

The same content is displayed for both. It's much easier to get it with a controller.

And you can see that the Principal contains User Details.

Summary

//controller
//Pass Principal principal as an argument
public ModelAndView userTop(eModelAndView mv, Principal principal) {
//controller
//Pass Principal principal as an argument
Authentication auth = (Authentication) principal;
//Get Principal from Authentication
String authClass = auth.getPrincipal()
   .getClass()
   .getSimpleName();

Recommended Posts

I want to get the information of the class that inherits the UserDetails class of the user who is logged in with Spring Boot.
[Rails] How to get the user information currently logged in with devise
I want to control the default error message of Spring Boot
[Spring Boot] I want to add my own property file and get the value with env.getProperty ().
I want to know the Method of the Controller where the Exception was thrown in the ExceptionHandler of Spring Boot
[Rails] Use devise to get information about the currently logged in user
My memorandum that I want to make ValidationMessages.properties UTF8 in Spring Boot
[Rails] How to temporarily save the request URL of a user who is not logged in and return to that URL after logging in
I want to get the value in Ruby
How to get the ID of a user authenticated with Firebase in Swift
Get the path defined in Controller class of Spring boot as a list
I always want to show what I posted only to myself who is logged in
I want to recursively get the superclass and interface of a certain class
05. I tried to stub the source of Spring Boot
[Spring Boot] Get user information with Rest API (beginner)
I tried to reduce the capacity of Spring Boot
Rails The concept of view componentization of Rails that I want to convey to those who want to quit
[Spring Boot] The story that the bean of the class with ConfigurationProperties annotation was not found
I tried to get started with Swagger using Spring Boot
[Ruby on Rails] I want to get the URL of the image saved in Active Storage
How to use the same Mapper class in multiple data sources with Spring Boot + MyBatis
I want to control the maximum file size in file upload for each URL in Spring Boot
I want to recreate the contents of assets from scratch in the environment built with capistrano
I want to understand the flow of Spring processing request parameters
Get a proxy instance of the component itself in Spring Boot
The story of Collectors.groupingBy that I want to keep for posterity
What I did in the migration from Spring Boot 1.4 series to 2.0 series
What I did in the migration from Spring Boot 1.5 series to 2.0 series
[Java] I want to perform distinct with the key in the object
[Spring Boot] Until @Autowired is run in the test class [JUnit5]
I want to change the value of Attribute in Selenium of Ruby
[Android] I want to get the listener from the button in ListView
Incident (rails) that is logged out when user editing of the application
To you who lament that the conversion of JODConverter + LibreOffice is slow
I want to display images with REST Controller of Java and Spring!
Autowired fields in a class that inherits TextWebSocketHandler in Spring Boot become NULL
Procedure to make the value of the property file visible in Spring Boot
[Note] I want to get in reverse order using afterLast with JdbcTemplate
I used Docker to solidify the template to be developed with spring boot.
I want to get the IP address when connecting to Wi-Fi in Java
I want to get the field name of the [Java] field. (Old tale tone)
[Java Spring MVC] I want to use DI in my own class
[Rails] [Parent-child relationship] I want to register the foreign key in the child with nil when the parent is deleted.
I tried to make a program that searches for the target class from the process that is overloaded with Java
[Rails] I want to reset everything because the data in the local environment is strange! What to do before that
I want to get the value of Cell transparently regardless of CellType (Apache POI)
I want to control the start / stop of servers and databases with Alexa
Organize the differences in behavior of @NotBlank, @NotEmpty, @NotNull with Spring Boot + Thymeleaf
Get the class name and method name of Controller executed by HandlerInterceptor of Spring Boot
[Java] Where is the implementation class of annotation that exists in Bean Validation?
I tried to clone a web application full of bugs with Spring Boot
How to set environment variables in the properties file of Spring boot application
I tried to make a web application that searches tweets with vue-word cloud and examines the tendency of what is written in the associated profile
I want to output the day of the week
The story of raising Spring Boot 1.5 series to 2.1 series
I want to var_dump the contents of the intent
How to create a class that inherits class information
I wanted to gradle spring boot with multi-project
I want to read the property file with a file name other than application.yml or application- [profile name] .yml with Spring Boot.
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (gray magic that is not so much as black magic)
I want to solve the problem that JS is not displayed properly unless reloaded when transitioning with Turbolinks: link_to