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:
References
- Getting Started with Spring Security
- Spring Security Role Based Authorization Example
- Spring Boot + Spring Security with JPA authentication and MySQL
Similar Posts
- Spring Boot Security- How to change default login page
- Spring Data JPA Derived Query Methods Example
- How to build executable JAR with Maven in Spring Boot
- How to send email using Spring Boot
- Spring Bean Life Cycle Management Example
- Spring Boot Security- Change default username and password parameter
- How to resolve Whitelabel Error Page in Spring Boot
- Versioning of REST API in Spring Boot: Types and Benefits
- Difference Between @Component and @ComponentScan Annotations in Spring Boot
- How to inject properties file data to bean in Spring