import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
private String getAgentId() {
SecurityContext securityContext = SecurityContextHolder.getContext();
if (securityContext.getAuthentication() instanceof EncryptAuthenticationToken) {
EncryptAuthenticationToken authenticationToken = (EncryptAuthenticationToken) securityContext.getAuthentication();
return authenticationToken.getUserDetails().getUsername();
} else if (securityContext.getAuthentication() instanceof UsernamePasswordAuthenticationToken){
User user = (User)securityContext.getAuthentication().getPrincipal();
return user.getUsername();
} else {
throw new HealthRuntimeException("8888", "认证方式失败");
}
}
【Spring】Spring Security 获取当前用户
最新推荐文章于 2024-08-23 10:50:07 发布