java - 在后端 Angular 10 + Spring Boot 中未正确接收授权标头
问题描述
我正在尝试将我的角度请求的“授权”标头中的 JWT 令牌传递给我的 Spring Boot 后端。
但是我的 Spring Back 并没有在标头中看到令牌,这会导致 cors 错误。当我从我的请求中检查标头时,令牌设置在“授权”标头中:
我来自 Spring Boot 的 JWTRequestFilter:
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
private JwtUserDetailsService jwtUserDetailsService;
private JwtTokenUtil jwtTokenUtil;
@Autowired
public JwtRequestFilter(JwtUserDetailsService jwtUserDetailsService, JwtTokenUtil jwtTokenUtil) {
this.jwtUserDetailsService = jwtUserDetailsService;
this.jwtTokenUtil = jwtTokenUtil;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
String username = null;
String jwtToken = null;
// JWT Token is in the form "Bearer token". Remove Bearer word and get
// only the Token
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
System.out.println("JWT Token has expired");
}
} else {
System.out.println(request.toString());
System.out.println(requestTokenHeader);
logger.warn("JWT Token does not begin with Bearer String");
}
// Once we get the token validate it.
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);
// if token is valid configure Spring Security to manually set
// authentication
if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// After setting the Authentication in the context, we specify
// that the current user is authenticated. So it passes the
// Spring Security Configurations successfully.
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
chain.doFilter(request, response);
}
}
当我打印时requestTokenHeader
is print null... 它还会在下面的打印语句中打印消息...
下面是我JWTinterceptor.ts
设置标题的地方:
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService, private localStorage: LocalStorageManagerService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add auth header with jwt if user is logged in and request is to the api url
const currentUser = this.authenticationService.currentUserValue;
const isLoggedIn = currentUser && this.localStorage.getToken();
const isApiUrl = request.url.startsWith(environment.apiUrl);
if (isLoggedIn && isApiUrl) {
console.log(this.localStorage.getToken());
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.localStorage.getToken()}`
}
});
}
return next.handle(request);
}
}
解决方案
推荐阅读
- sql - SQL Server:如何仅获取树的最新(最深)节点
- ios - 如何在iOS(Xcode)中的提交按钮内实现分段控制?
- python - 没有名为“prompt_toolkit.formatted_text”的模块
- python - python shell和IDLE有什么区别?
- php - MYSQL:将变量插入变量名表
- javascript - 如何在 Laravel 中合并两个图像
- latex - 用箭瞄准目标
- java - 我有两个 Java 类并且有 @ManyToOne 并且我不想在第二个 Java 类中使用 @Audit
- git - 如何从 Gitlab 签出 git 分支到 Android Studio
- javascript - 获取当前标签页 url - Chrome 扩展