'How to pass token in header section in authorization field in angular

I got token and stored in "this.token" as

this.token = Venktoken;      
console.log(this.token);

When I tried to pass the token values in header section am not getting any results. I tired to pass like,

{headers: new HttpHeaders({
'Authorization': 'bearer '+ this.token,

How to pass the token in header section



Solution 1:[1]

Regarding the best way of handling Authentication headers in Angular > 4 it's best to use Http Interceptors for adding them to each request, and afterwards using Guards for protecting your routes.

Here's a full example of an AuthInterceptor that I'm using in my app:

auth.interceptor.ts

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';

import { AuthService } from './auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    req = req.clone({
      setHeaders: {
        'Content-Type' : 'application/json; charset=utf-8',
        'Accept'       : 'application/json',
        'Authorization': `Bearer ${AuthService.getToken()}`,
      },
    });
    return next.handle(req);
  }
}    

You'll need to register your interceptor in the app.module as a provider:

app.module.ts


import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { AuthInterceptor } from '../auth/auth.interceptor';

...

imports: [
    HttpClientModule,
    ...
],
providers: [
    {
      provide : HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi   : true,
    },
    ...
],

...

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

Regarding the Go's side of things, this is most likely a case of mismatch between Request Headers you're sending and the headers CORS allow. First thing you should try is allowing all of them:

headersOk := handlers.AllowedHeaders([]string{"*"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

And if the problem goes away try carefully structuring your CORS one by one to what your client is sending.

Solution 2:[2]

Try like this:

import { HttpClient, HttpResponse ,HttpHeaders} from '@angular/common/http';

let header = new HttpHeaders().set("Authorization", 'Bearer ' + this.token);

return this.http.post(this.api_url,null, header);

To set multiple headers, try like this:

let headers = new HttpHeaders()
    .set('Authorization', 'Bearer ' + this.token)
    .set('Content-Type', 'application/json')
    .set('InstanceName', 'ORISSA');

return this.http.post(this.api_url,null, headers );

Solution 3:[3]

As alternative method you can try to use this library angular-jwt It provides a HttpInterceptor out of the box which automatically attaches token to HttpClient requests.

Also it has lots of build-in helpers like isTokenExpired, decodeToken, etc within JwtHelperService. You can set it up as a module:

JwtModule.forRoot({
  config: {
    // ...
    headerName: 'Authorization',
    tokenGetter: () => {
      return localStorage.getItem('access_token');
    }
  }
});

The above example using localStorage but you can store the token anywhere on the client based on your exact use-case.

Solution 4:[4]

Short Answer

    let headers = new HttpHeaders()
          .set('Authorization', 'Bearer ' + token)
          .set('Content-Type', 'application/json'); 

    this.http.put(`${url}`, null, { headers });

    this.http.get(`${url}`, { headers });

    this.http.delete(`${url}`, { headers });

More Details (How I found out)?

When you hover on the function you will find headers under options object not directly.

headers can be of type HttpHeaders or string. I prefer using HttpHeaders as I showed you.

enter image description here

Solution 5:[5]

I have got similar problem like this and this works for me

  1. create a constant called httpOptions to catch the value of headers:
    const httpOptions = { 
headers: new HttpHeaders({
    'Content-Type': 'application/json',
    Authorization: 'my-auth-token',
  })
};
  1. Inside of your service create get method that holds your token value, and set the httpOptions header to what you have got from that method.
    getUser(myToken:any){
     httpOptions.headers = httpOptions.headers.set('Authorization',myToken);
    
     return this.http.get(this.usersUrl,httpOptions);
    }
  1. call the service inside your component and pass the token value:
    this.auth.getUser(this.tokenValue).subscribe(
      response => {
        console.log(response)
      }
    )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sanjay Lohar
Solution 2
Solution 3
Solution 4 Mansour Alnasser
Solution 5