Я пытаюсь реализовать JWT-аутентификацию в моем Angular приложении с помощью Django backend. Я думал, что это сработало, но теперь все запросы POST не получают заголовок Authenication, что приводит к 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],
Я уже довольно давно не могу решить эту проблему, любая помощь приветствуется.