Angular 安全拦截器未在 POST 请求上添加身份验证 headers

Angular security interceptor not adding Authentication headers on POST request

我正在尝试在我的 Angular 应用程序中使用 Django 后端实施 JWT 身份验证。我认为它有效,但现在所有 POST 请求都没有收到身份验证 header,这导致 401。我对 Angular

很陌生

security.interceptor.ts

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { Router } from '@angular/router';
import { UserService } from 'src/app/services/user.service';

/**
 * Securityinterceptor
 */
@Injectable()
export class SecurityInterceptor implements HttpInterceptor {
  /**
   * Constructor
   * @param router
   * @param userService
   * @param http
   */
  constructor(private router: Router, private userService: UserService, private http: HttpClient) { }
  /**
   * Intercepts http requests. Adds authorization headers to request and re-executes request.
   * When access token is expired, the interceptor will try to refresh the accestoken and re-executes the request.
   * If the interceptor can't refresh tokens, it will throw an error
   * @param request 
   * @param next 
   */
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let token = localStorage.getItem('token');
    if (token) {
      request = request.clone({
        headers: request.headers
          .set('Content-Type', 'application/json')
          .set('Authorization', 'JWT ' + token)
      });
    }

    return next.handle(request).pipe(
      catchError(err => {
        console.log(err);
        if (err.status === 401) {
          // Generate parameters for token refreshing
          if (err.error.messages[0].message == "Token is invalid or expired") {
            let refresh = JSON.stringify({
              refresh: localStorage.getItem('refreshToken')
            });
            // Reload tokens
            this.userService.refreshToken(refresh).subscribe(result => {
              localStorage.setItem('token', result.access);
              localStorage.setItem('refreshToken', result.refresh);

              request = request.clone({
                headers: request.headers
                  .set('Content-Type', 'application/json')
                  .set('Authorization', 'JWT ' + result.access)
              });
              location.reload(true);
            });
          } else {
            this.userService.logout(localStorage.getItem('refreshToken'));
          }
        return throwError(err);
        }
      }));
  }
}


app.module.ts

providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: SecurityInterceptor,
    multi: true
  }, GlobalVariablesService],

我已经有一段时间没能解决这个问题了,感谢任何帮助。

您可以使用 setHeader 参数设置 header。 试试这个:

if (token) 
{
      request=req.clone({ setHeaders: { Authorization: 'JWT ' + token } });
}