Angular 7 - Send token in a post web service

Viewed 9388

I´m trying to send token header in a http.post. I try this code but return in browser log:

Access Denied

const httpOptions = {
      headers: new HttpHeaders({
        "Authorization": "Token " + localStorage.getItem("token")
      })
    };

      getCron() {
        console.log(httpOptions);
        return this.http.post(
          "URL", httpOptions);
      }

console.log return the correct token, so this isn´t the error. The error is that i don´t know how to add exactly header token in the call. So the question is: How can i add this token in the call?

4 Answers

This is because the post() method accepts a request body as a second argument, to http options should be the third argument.

const httpOptions = {
      headers: new HttpHeaders({
        "Authorization": "Token " + localStorage.getItem("token")
      })
    };

      getCron() {
        console.log(httpOptions);
        return this.http.post(
          "URL", null, httpOptions); // replace the null with a body
      }

If you don't have any data to post, you may want to change the endpoint to a GET in stead of a POST.

Try this:

headers = new HttpHeaders({ 'Authorization': 'Bearer ' + localStorage.getItem("token") });

Then call the http request using new headers:

this.http.get(url, { headers: this.headers }).subscribe(...);

Try this :

 import { Http, Headers, RequestOptions} from '@angular/http';

 var headers = new Headers();
 headers.append('Authorization', 'Bearer ' + localStorage.getItem("token"));
 headers.append('Content-Type', 'application/json');
 let options = new RequestOptions({ headers: headers });
 this.http.post(url, options).map(...);

Use interceptors to append a token to every HTTP request. Store the token in a user object and use an Auth service to retrieve it.

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthenticationService } from '../service/Authentication/authentication-service.service';



@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        let currentUser = this.authenticationService.currentUserValue;
        if (currentUser && currentUser.token) {
           request = request.clone({ headers: request.headers.append('Authorization', 'Bearer '+ currentUser.token) });  
           
        }

        return next.handle(request`enter code here`);
    }
}

Related