我目前正在做一个Spring+Angular项目。当我尝试拦截请求并将其标头设置为angular时,Spring 找不到授权标头。
我的 JwtRequestFilter 看起来像这样:
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
private MyUserDetailsService userDetailsService;
private JwtUtil jwtUtil;
@Autowired
public JwtRequestFilter(MyUserDetailsService userDetailsService,
JwtUtil jwtUtil) {
this.userDetailsService = userDetailsService;
this.jwtUtil = jwtUtil;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
final String authorizationHeader = request.getHeader("Authorization");
/*Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
System.out.println("Header " + headerNames.nextElement());
}*/
Enumeration<String> blabla = request.getHeaderNames();
while (blabla.hasMoreElements()) {
String header = blabla.nextElement();
System.out.println("Header " + header);
System.out.println("Value " + request.getHeader(header));
}
String username = null;
String jwt = null;
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails ud = this.userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(jwt, ud)) {
UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(ud,
null,ud.getAuthorities());
upat.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(upat);
}
}
response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Expose-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
filterChain.doFilter(request, response);
}
}
而 Angular HTTPInterceptor 类:
@Injectable()
export class TokenInterceptorService implements HttpInterceptor {
constructor(private injector: Injector) { }
intercept(req : HttpRequest<any>, next: HttpHandler) {
let token = localStorage.getItem('jwt');
const lo = /login/gi;
const re = /register/gi;
if (req.url.search(re) === -1 && req.url.search(lo) === -1) {
let authService = this.injector.get(UserService);
let update = {
headers: req.headers.set('Authorization', `Bearer ${token}`)
};
req = req.clone(update)
console.log(req)
}
return next.handle(req);
}
}
我也尝试调试它,但request.getHeader总是得到空值,但是如果我尝试Postman,它工作正常。 当我尝试使用 Spring 打印出所有标题时,没有用于授权的标题,所以我怀疑这是一个 Angular 方面的问题。
在角度侧: 控制台日志 如图所示,标头应该获得授权,持有者。 网络源
目前我不知问题可能是什么。
所以WebSecurityConfigurer中缺少一个configure.cors((,这解决了它。