Search code examples
angulardjango-rest-frameworksingle-page-applicationangular5django-rest-framework-jwt

set JWT token in header in angular 5 app


hi im working on django rest framwork for backend and angular 5 app as client .. i need to send JWT token and Content-Type in each request to server how can i set "jsonwebtoken" and "content-type" in request header???? looks like RequestOptions and Header are deprecated in angular 5 any solution???

import {Injectable} from '@angular/core';
import {Headers, RequestOptions} from '@angular/http'
import {HttpClient} from "@angular/common/http";
import 'rxjs/add/operator/map'


@Injectable()
export class UserService {

  private options;
  constructor(private http: HttpClient) {
    const token = localStorage.getItem('theuser');

    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', 'Bearer' + ' ' + token)
    this.options = new RequestOptions({headers: headers});

    console.log(this.options)
  }


  userInfo() {
    return this.http.get<any>("http://localhost:8000/user-detail/",this.options)

  }

}

Solution

  • You can extend the http interceptor class. Create new service token.interceptor.ts with following content.

    import { Injectable } from '@angular/core';
    
    import {
      HttpRequest,
      HttpHandler,
      HttpEvent,
      HttpInterceptor
    } from '@angular/common/http';
    import { Observable } from 'rxjs/Observable';
    declare var localStorage : any;
    
    @Injectable()
    export class TokenInterceptor implements HttpInterceptor {
      constructor() {}
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let allowedUrls =( request.url.indexOf("dealer/signup") < 0 && request.url.indexOf("dealer/login") < 0 );   
    
        if(allowedUrls){
    
            let authToken = localStorage.getItem("dealertoken");
            request = request.clone({
                headers: request.headers.set('Authorization', 'Bearer '+ authToken)
                /* setHeaders: {
                    Authorization: 'Bearer '+ authToken
                } */
            });
        }
        return next.handle(request);
      }
    }
    

    and import it in app.module.ts

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