SpringSecurity中,如何获取实现 UserDtails 的类的数据
时间: 2024-04-15 13:08:04 浏览: 17
在 Spring Security 中,可以通过 `SecurityContextHolder` 类中的 `getContext()` 方法获取当前的 `SecurityContext`,再通过 `SecurityContext` 中的 `getAuthentication()` 方法获取当前用户的 `Authentication` 对象。接着,可以通过 `Authentication` 对象的 `getPrincipal()` 方法获取当前用户的主体信息,如果该主体信息是一个实现了 `UserDetails` 接口的类,那么就可以强制类型转换为 `UserDetails` 类型,并获取其中的数据。
示例代码如下:
```java
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails) {
UserDetails userDetails = (UserDetails) principal;
// 获取 UserDetails 中的数据
String username = userDetails.getUsername();
String password = userDetails.getPassword();
Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
// ...
}
```
其中,`getUsername()` 方法获取用户的用户名,`getPassword()` 方法获取用户的密码,`getAuthorities()` 方法获取用户的权限列表。当然,这些方法的具体实现可能会因为不同的实现类而有所不同。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)