From def8ac7a6c12a30b7dc89e21252246a04343c9ea Mon Sep 17 00:00:00 2001 From: ovo Date: Sat, 7 Dec 2024 18:55:49 +0800 Subject: [PATCH] =?UTF-8?q?=E7=99=BB=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../backend/service/impl/UserServiceImpl.java | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/guwan/backend/service/impl/UserServiceImpl.java b/src/main/java/com/guwan/backend/service/impl/UserServiceImpl.java index 82be70d..8a4e0f7 100644 --- a/src/main/java/com/guwan/backend/service/impl/UserServiceImpl.java +++ b/src/main/java/com/guwan/backend/service/impl/UserServiceImpl.java @@ -17,6 +17,10 @@ import com.guwan.backend.vo.user.PhoneRegisterRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -157,7 +161,21 @@ public class UserServiceImpl implements UserService { @Override public Long getCurrentUserId() { - // TODO: 从SecurityContext中获取当前用户ID + // 从SecurityContext中获取认证信息 + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + + // 如果没有认证信息,返回null + if (authentication == null || !authentication.isAuthenticated() || + authentication instanceof AnonymousAuthenticationToken) { + return null; + } + + // 获取UserDetails + Object principal = authentication.getPrincipal(); + if (principal instanceof CustomUserDetails) { + return ((CustomUserDetails) principal).getUserId(); + } + return null; }