Skip to content
Advertisement

How to get user id with Spring MVC?

I using the POST method for add Item to the database with Spring MVC. But each Item has field userId, it FOREIGN KEY to users table. Need to know user’s id for this. I using Spring security for auth. May be there is a possibility get current user’s id with ServletContext or HttpSession, may be spring security save user’s id somewhere?

How to identify user which requested to the server with Spring MVC to data in the database?

JavaScript

Spring security implementation with using UserDetails so all details hidden from me, and I don’t know how to intervene in auth process and intercept user’s id in the authorysation stage.

JavaScript

Thank You!

Advertisement

Answer

Please try with this approach

Make sure that you have your own User pojo class

JavaScript

Also an Authority pojo in order to define the user roles

JavaScript

Then the user repository, in this example I just declare a method to find by username and get an Optional to validate if the user exists.

JavaScript

Create a user class that extends from org.springframework.security.core.userdetails.User in order to wrap your custom user inside the definition of the spring security user.

JavaScript

And now the UserDetailService implementation, there is just one method to implement loadUserByUsername here is where the MyUserRepository is needed, in order to retrieve the user information from the repository by the username.

JavaScript

And now you can inject the UserDetailService because its implementation will be injected form MyUserService class.

JavaScript

then with this approach you can inject the Principal object to your controller, and inside the method you can cast the Principal object to MySpringUser, it is because MySpringUser is extended from org.springframework.security.core.userdetails.User and User class implements the UserDetails interface. Of course you can get all the rest of custom fields of the user because its definition is wrapped inside the org.springframework.security.core.userdetails.User class

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement