How to get user details in Spring Security

This article will focus on how to retrieve the user details in Spring Security. To get current logged-in user details like username and role Spring Security provide an Authentication interface.

It represents the token for an authentication request or for an authenticated principal once the request has been processed by the authenticate(Authentication authentication) method of AuthenticationManager.

Let’s jump to the actual part of coding.

1. Create some dummy users:

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
			.password(passwordEncoder().encode("[email protected]")).roles("ADMIN")
			.password(passwordEncoder().encode("[email protected]")).roles("USER");

	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();

2. Controller class to fetch logged-in user information:

public class UserController {

	public String userInfo(Authentication authentication) {

		String userName = authentication.getName();
		String role = authentication.getAuthorities().stream()

		return "Your user name is: " + userName + " and your role is: " + role;


2.1 User authority/role can retrieve by user Enhanced-For-Loop also:

String role = "";
for (GrantedAuthority authority : authentication.getAuthorities()) {
	role = authority.getAuthority();

Alternatively, we can also use the getPrincipal() method:

UserDetails userDetails = (UserDetails) authentication.getPrincipal();
System.out.println("User has authorities: " + userDetails.getAuthorities());


After the successful login, you will get the current logged-in user details as shown below:

How to get user details in Spring Security


  1. Getting Started with Spring Security
  2. Spring Security Role Based Authorization Example
  3. Spring Boot + Spring Security with JPA authentication and MySQL

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.