| | |
| | | return userId; |
| | | } |
| | | |
| | | if (token == null) { |
| | | logger.debug("未能从请求头获取到JWT token"); |
| | | } else { |
| | | logger.debug("从请求头获取到token但校验失败"); |
| | | } |
| | | |
| | | // 如果没有有效的JWT token,尝试从Spring Security上下文获取 |
| | | Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); |
| | | if (authentication != null && authentication.isAuthenticated() && |
| | |
| | | private String getTokenFromRequest() { |
| | | try { |
| | | ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); |
| | | if (attributes != null) { |
| | | if (attributes == null) { |
| | | logger.warn("RequestContextHolder中无ServletRequestAttributes,可能为异步执行或非Servlet环境"); |
| | | } else { |
| | | HttpServletRequest request = attributes.getRequest(); |
| | | String authHeader = request.getHeader("Authorization"); |
| | | logger.debug("读取到Authorization头: {}", authHeader); |
| | | if (authHeader != null && authHeader.startsWith("Bearer ")) { |
| | | return authHeader.substring(7); |
| | | String token = authHeader.substring(7); |
| | | logger.debug("从Authorization头提取到Bearer token,长度: {}", token != null ? token.length() : 0); |
| | | return token; |
| | | } else { |
| | | logger.debug("Authorization头不存在或不以Bearer开头"); |
| | | } |
| | | } |
| | | } catch (Exception e) { |