2
votes

I want to add Authorization Headers to a Post request after researching a lot over the web and trying all possible ways of adding headers to a request i still couldn't make it happen i need to authenticate the post request of my angular app to django server

headers2 = {
    "Content-Type": "application/json",
    "Authorization": "JWT " + token
}
json_data = json.dumps({"content":" content nice content"})
posted_response = requests.post(ENDPOINT, data=json_data, headers=headers2)

when i fired this code it's running perfectly fine and adding it my data base using python requests i assumed the process would be same for angular as well and added authorization headers directly to the headers of http post request

createPost(input:HTMLInputElement){
    // input.value='';
    let post={content:input.value};
    let head = new Headers({ 'Content-Type': 'application/json',
    // 'Authorization': "JWT"+'Bearer '+localStorage.getItem("token")
    "Authorization": "JWT " + localStorage.getItem("token")

  });
    let requestOptions = new RequestOptions({headers: head});
    let body = JSON.stringify(post);

    this.http.post(this.url,body,requestOptions)
      .subscribe(response =>{
        post['id']=response.json().id;
        this.posts.splice(0,0,post);


      });

the token value is stored in localstorage

but it didn't work so after crawling over google and all i came to know about Http Interceptors created a service and tried to add the authorization to them

@Injectable({
  providedIn: 'root'
})
export class AuthoService  implements HttpInterceptor {

  constructor() { }
  intercept(req,next){
    let tokenizedReq =req.clone({
      setHeaders:{
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    return next.handle(tokenizedReq)


  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   let ok = JSON.parse(localStorage.getItem('token'));

    req = req.clone({

      setHeaders: {
        'Content-Type' : 'application/json; charset=utf-8',
        'Accept'       : 'application/json',
        // 'Authorization': "JWT" + `Bearer ${localStorage.getItem('token')}`
        'Authorization': "JWT" + `Bearer ${ok.token}`

      }
    });

    return next.handle(req);
  }
}

Tried the best ways possible but still its of no use so i assumed i might have done somewhere wrong so decided to learn the http Interceptor stuff from scratch

I followed this tutorial https://www.youtube.com/watch?v=UrfhqE7I-3o

i followed each and every step he told me to do so for adding headers to my reuqest

@Injectable({
  providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor{

  constructor() { }
intercept(req,next){

  let tokenizedreq=req.clone({

    setHeaders:{
      Authorization:'Bearer xx.yy.zz'
    }

  })
  return next.handle(tokenizedreq)
}


}

and added it app.modules.ts

providers: [CourseService,AuthService,
    {
      provide : HTTP_INTERCEPTORS,
      useClass: TokenInterceptorService,
      multi   : true,
    }],

but still i don't understand what the issue is and why authorization headers aren't in my request any kind of help is appreciated

1
Can you add console log please? - Naou

1 Answers

0
votes

This is a sample code for using authorization in angular, when backend is django. I hope it help you.

If you are using JWT django framework for authentication, you can do like this in angular :

createComment(aComment: any){
    let url = this.mainUrl + '/api/comment/create/?format=json';
    let headers = new Headers();

    if(localStorage.getItem('token') !== ''){
      headers = new Headers({ 'Authorization': 'JWT ' +localStorage.getItem('token') });
    }else{
      headers = new Headers({});
    }
    let options = new RequestOptions({ headers: headers });

    return this.http.post(url, aComment, options)
      .map(
        (response: Response) => {
          const data = response.json();
          return data;
        }
      )
      .catch(
        (error: Response) => {
          let rr = error.json();
          return Observable.throw(rr.errorMessage);
        }
      );
  }
}

and in django you can do just like this :

class CommentCreateAPIView(CreateAPIView):

    serializer_class = serializers.CommentCreateSerializer
    permission_classes = (permissions.IsAuthenticated, )

    queryset = Comment.objects.all()