获取当前用户的信息

This commit is contained in:
Bunny 2025-07-11 16:19:56 +08:00
parent 8b6dba3749
commit 95cb8bfa86
3 changed files with 63 additions and 0 deletions

View File

@ -293,4 +293,51 @@ public class CustomUserDetailsService implements UserDetailsService {
.build();
}
}
```
## 当前用户登录信息
用户的信息都保存在`SecurityContextHolder.getContext()`的上下文中。
```java
/**
* 获取当前认证用户的基本信息
* 使用Spring Security的SecurityContextHolder获取当前认证信息
*/
@Operation(summary = "当前用户的信息", description = "当前用户的信息")
@GetMapping("/current-user")
public Authentication getCurrentUser() {
// 从SecurityContextHolder获取当前认证对象
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
// 打印当前用户名和权限信息到控制台(用于调试)
System.out.println("Current user: " + auth.getName());
System.out.println("Authorities: " + auth.getAuthorities());
// 返回完整的认证对象
return auth;
}
/**
* 获取当前用户的详细信息
* 从认证主体中提取UserDetails信息
*/
@Operation(summary = "获取用户详情", description = "获取用户详情")
@GetMapping("user-detail")
public UserDetails getCurrentUserDetail() {
// 从SecurityContextHolder获取当前认证对象
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
// 获取认证主体(principal)
Object principal = auth.getPrincipal();
// 检查主体是否是UserDetails实例
if (principal instanceof UserDetails) {
// 如果是则转换为UserDetails并返回
return (UserDetails) principal;
} else {
// 如果不是UserDetails类型返回null
return null;
}
}
```

View File

@ -1,8 +1,10 @@
package com.spring.step2.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@ -12,6 +14,7 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/api/security")
public class CheckController {
@Operation(summary = "当前用户的信息", description = "当前用户的信息")
@GetMapping("/current-user")
public Authentication getCurrentUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
@ -20,4 +23,17 @@ public class CheckController {
return auth;
}
@Operation(summary = "获取用户详情", description = "获取用户详情")
@GetMapping("user-detail")
public UserDetails getCurrentUserDetail() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object principal = auth.getPrincipal();
if (principal instanceof UserDetails) {
return (UserDetails) principal;
} else {
return null;
}
}
}