How to pass Authorization Header Token in api call in angular

17,462

Solution 1

Try like this:

Use HttpClient

import { Injectable } from "@angular/core";
import { HttpClient,HttpHeaders  } from '@angular/common/http';

@Injectable()
export class ApiService {
  constructor(private http: HttpClient) {}

  getTransferIp() {
    let header = new HttpHeaders().set(
      "Authorization",
       localStorage.getItem("token")
    );

    return this.http.get("http://localhost:3003/transferip", {headers:header});
  }
}

Solution 2

To intercept http requests in angular, you can write a service that implements HttpsInterceptor interface from common/http module.

 @Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor() { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = 'token...'; // your auth token
    if (authorized) { // your authorized  logic
      request = request.clone({
        setHeaders: {
          Authorization: `${token}`
        }
      });
    }

    return next.handle(request);
  }
}

Don't forget providing your service in your module.ts file

{provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor},

Solution 3

You can create an interceptor to add the Authorization header for every request.

https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8

If you want to add the header for only this specific request, temporarily, you can use something like this.

getTransferIp(){ {
    const token = localStorage.getItem("token");
    const header = new Headers({ 'Authorization': `Bearer ${token}` });
    const options = {
       headers: header,
    };

    return this.http.get('http://localhost:3003/transferip', options);   
}
Share:
17,462

Related videos on Youtube

Aayush Gupta
Author by

Aayush Gupta

Beginner in MEAN Stack. Past worked in PHP/MySQL. Aspiring to learn more.

Updated on June 04, 2022

Comments

  • Aayush Gupta
    Aayush Gupta almost 2 years

    I am using a get api call to fetch the data from json doc using http. But i have enabled authorization to only token bearer. I want to pass the value of token (which i can get through localStorage.getItem("token");) in my Authorization in the headers when i call the get request.

    API.SERVICE.TS

    import { Injectable } from '@angular/core';
    import { Http, Headers, RequestOptions } from '@angular/http';
    import { Observable } from 'rxjs';
    import { HttpClientModule } from '@angular/common/http';
    import { HttpClient, HttpRequest, HttpEventType, HttpHeaders, HttpParams, HttpEvent, HttpErrorResponse, HttpResponse } from '@angular/common/http';
    
    import 'rxjs/add/operator/map';
    
    @Injectable({
      providedIn: 'root'
    })
    export class ApiService {
    
      constructor(private http: Http) { }
    
      getTransferIp(){
        return this.http.get('http://localhost:3003/transferip').map(res => res.json() );
      }
    
    }
    

    Currently i am allowed to fetch the data only when i turn off the auth in my node server get router... But i dont want to do that and also without using interceptor

    Attatching Node Server Files below...

    AUTH.JS

    const jwt = require('jsonwebtoken')
    const User = require('../models/user')
    
    const auth = async (req, res, next) => {
        try {
            const token = req.header('Authorization').replace('Bearer ', '')
            const decoded = jwt.verify(token, 'mango@123')
            const user = await User.findOne({ _id: decoded._id, 'tokens.token': token })
    
            if (!user) {
                throw new Error()
            }
    
            req.token = token
            req.user = user
            next()
        } catch (e) {
            res.status(401).send({ error: 'Please authenticate.' })
        }
    }
    
    module.exports = auth
    

    TRANSFERIP.JS (ROUTER)

    const express = require('express')
    const TransferIp = require('../models/transferip')
    const auth = require('../middleware/auth')
    const router = new express.Router()
    
    router.post('/transferip', auth, async (req, res) => {
        const task = new TransferIp({
            ...req.body,
            owner: req.user._id
        })
    
        try {
            await task.save()
            res.status(201).send(task)
        } catch (e) {
            res.status(400).send(e)
        }
    })
    router.get('/transferip', auth, function(req, res, next) {
        TransferIp.find(function (err, events) {
          if (err) return next(err);
          res.json(events);
        });
    });
    
    module.exports = router
    

    SCREENSHOT OF SUCCESSFUL GET REQUEST WITH TOKEN USING POSTMAN enter image description here

  • Jason White
    Jason White over 4 years
    in the network tab of your browser, does the request contain the Authorization header?
  • Aayush Gupta
    Aayush Gupta over 4 years
    yes it does. and fyi when i get the request through postman adding the token, it works
  • Adrita Sharma
    Adrita Sharma over 4 years
    Why are you using map, which version of Angular are u using
  • Jason White
    Jason White over 4 years
    Is it a cors issue? Is there an options request before the api request that fails? In the console of the browser, is there a Cross Origin error?
  • Aayush Gupta
    Aayush Gupta over 4 years
    im using 8.2 btw getting this error while trying ur answer ``` Argument of type 'HttpHeaders' is not assignable to parameter of type 'RequestOptionsArgs'. Property 'headers' is private in type 'HttpHeaders' but not in type 'RequestOptionsArgs' ```
  • Adrita Sharma
    Adrita Sharma over 4 years
    Use httpclient, constructor(private http: HttpClient) { }
  • Adrita Sharma
    Adrita Sharma over 4 years
    Can you try the latest?
  • Aayush Gupta
    Aayush Gupta over 4 years
    tried. no luck :( btw im not getting the 2nd comment error. but i am not able to fetch the data as i am getting 401:unauthorized
  • Adrita Sharma
    Adrita Sharma over 4 years
    What kind of authorization does your backend have? Btoa? Bearer? Try it using postman and show how it worked
  • Aayush Gupta
    Aayush Gupta over 4 years
    i have added more details in the question. please check
  • Adrita Sharma
    Adrita Sharma over 4 years
    In authorization header, before the value, you didn't append 'Bearer' or anything else?
  • Adrita Sharma
    Adrita Sharma over 4 years
    Check the modified answer. Remove "Bearer " +
  • Aayush Gupta
    Aayush Gupta over 4 years
    tried but still noo.... GET http://localhost:3003/transferip 401 (Unauthorized)
  • Adrita Sharma
    Adrita Sharma over 4 years
    Well, No idea then, this the way this is done. You can check localStorage.getItem("token") if this correct
  • Petar
    Petar almost 4 years
    @JasonWhite yes, I have similar issue, and I get CORS error, even tho I have CORS handling on backend, can you help here? Also I have slightly different issue since I am using angular 9.
  • Jason White
    Jason White almost 4 years
    @Petar If you're getting a CORS issue, there is most likely something wrong with the way your backend is configured. CORS request are sent/handled by the browser and not Angular so the issue is most likely not Angular related. Without seeing any source code, it's hard to tell the issue.