0

I'm trying to implement JWT authentication in my Angular application with a Django backend. I thought it worked but now all the POST requests don't receive the Authenication header, which results in a 401. I'm quite new to 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],

It's been quite some time that I haven't been able to fix this problem, any help is appreciated.

4
  • did you check in network tab if the header is present or not Commented May 7, 2020 at 9:21
  • try to put breakpoint where you add headers in chrome dev tools and see if the code gets executed Commented May 7, 2020 at 9:22
  • you have to use the setHeaders param Commented May 7, 2020 at 9:24
  • The headers are not present in the network tab. I'll try the setHeaders parameter! Commented May 7, 2020 at 9:32

1 Answer 1

2

you can set the the header by using the setHeader param . try this:

if (token) 
{
      request=req.clone({ setHeaders: { Authorization: 'JWT ' + token } });
}
Sign up to request clarification or add additional context in comments.

1 Comment

This fixed my problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.