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:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication()
			.withUser("manish")
			.password(passwordEncoder().encode("admin@123")).roles("ADMIN")
			.and()
			.withUser("sandeep")
			.password(passwordEncoder().encode("user@123")).roles("USER");
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
}

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

@RestController
public class UserController {

	@GetMapping("/user")
	public String userInfo(Authentication authentication) {

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

		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());

Output:

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

How to get user details in Spring Security

References

  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.