本文将重点介绍如何在 Spring Security 中检索用户详细信息。 要获取当前的登录用户 详细信息,例如用户名和角色,Spring Security 提供 Authentication
接口。
一旦请求被 AuthenticationManager
的 authenticate(Authentication *authentication*)
方法处理,它代表身份验证请求或已验证主体的令牌。
让我们跳到编码的实际部分。
1. 创建一些虚拟用户:
@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. 获取登录用户信息的控制器类:
@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 也可以由用户 Enhanced-For-Loop 检索:
String role = "";
for (GrantedAuthority authority : authentication.getAuthorities()) {
role = authority.getAuthority();
}
或者,我们也可以使用 getPrincipal()
方法:
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
System.out.println("User has authorities: " + userDetails.getAuthorities());
输出:
成功登录后,您将获得当前已登录用户的详细信息,如下所示:
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.websparrow.org/spring/how-to-get-user-details-in-spring-security
内容来源于网络,如有侵权,请联系作者删除!