22

Currently I used this static code in component .ts file but this one is not work. It returns unauthorized(401). But when I pass token as query string it works fine. Please give a working example for component .ts file.

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


    var t=`eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTUzNzcxNTMyNSwiZXhwIjoxNTM3NzE4OTI1LCJuYmYiOjE1Mzc3MTUzMjUsImp0aSI6IlBKWVhnSkVyblQ0WjdLTDAiLCJzdWIiOjYsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.1vz5lwPlg6orzkBJijsbBNZrnFnUedsGJUs7BUs0tmM`;

    var headers_object = new HttpHeaders();
        headers_object.append('Content-Type', 'application/json');
        headers_object.append("Authorization", "Bearer " + t);

        const httpOptions = {
          headers: headers_object
        };


   this.http.post(
                  'http://localhost:8000/api/role/Post', {limit:10}, httpOptions
                 ).subscribe(resp => {
                  this.roles = console.log(resp)
                  }
                );
tufac2
  • 668
  • 6
  • 7
Sumit
  • 1,702
  • 2
  • 14
  • 20

5 Answers5

33

Add AuthInterceptor that will intercept all your http requests and add the token to its headers:

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

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = localStorage.token; // you probably want to store it in localStorage or something

    if (!token) {
      return next.handle(req);
    }

    const req1 = req.clone({
      headers: req.headers.set('Authorization', `Bearer ${token}`),
    });

    return next.handle(req1);
  }

}

Then register it in your AppModule:

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
  ],
  bootstrap: [ AppComponent ],
})
export class AppModule { }

More about interceptors:

https://angular.io/guide/http#intercepting-requests-and-responses

Martin Adámek
  • 16,771
  • 5
  • 45
  • 64
22

The problem with your code is that the HttpHeaders class is immutable, so when you call append it actually returns a new instance with the specified value, but does not modify the original object.

Try this

var headers_object = new HttpHeaders().set("Authorization", "Bearer " + t);

Content-Type is set to json by default by HttpClient

If you need to do send a the Authorization token in all your API calls, then it's better to use an interceptor as suggested by Martin

David
  • 33,444
  • 11
  • 80
  • 118
  • Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403. I don't why this error is coming, because its working fine with query string. – Sumit Sep 24 '18 at 04:49
  • 2
    Now that means that the header is sent correctly, but you have a CORS issue. You need to configure your API to handle CORS, which is a different topic – David Sep 24 '18 at 05:52
  • 1
    Because when using query string, it does not add a custom header – David Sep 24 '18 at 06:04
  • 1
    Thanks man finally solved my issue, you are correct, it was CORS issue after follow your steps. – Sumit Sep 24 '18 at 06:46
4

Another solution is to use angular-jwt: https://github.com/auth0/angular2-jwt

No need to create an interceptor just update your AppModule:

import { JwtModule } from "@auth0/angular-jwt";
import { HttpClientModule } from "@angular/common/http";

export function tokenGetter() {
    return localStorage.getItem('access_token');
}

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        HttpClientModule,
        JwtModule.forRoot({
            config: {
                tokenGetter: tokenGetter,
                allowedDomains: ['localhost:3000', 'example.com'],
                disallowedRoutes: ["http://example.com/examplebadroute/"],
                authScheme: "Bearer " // Default value
            }
        })
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Any requests sent using Angular's HttpClient will automatically have a token attached as an Authorization header.

Emeric
  • 6,315
  • 2
  • 41
  • 54
3

Please create HttpHeaders object like this (instead of appending) ,

var t="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTUzNzcxNTMyNSwiZXhwIjoxNTM3NzE4OTI1LCJuYmYiOjE1Mzc3MTUzMjUsImp0aSI6IlBKWVhnSkVyblQ0WjdLTDAiLCJzdWIiOjYsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.1vz5lwPlg6orzkBJijsbBNZrnFnUedsGJUs7BUs0tmM";

    var headers_object = new HttpHeaders({
      'Content-Type': 'application/json',
       'Authorization': "Bearer "+t)
    });

        const httpOptions = {
          headers: headers_object
        };


   this.http.post(
                  'http://localhost:8000/api/role/Post', {limit:10}, httpOptions
                 ).subscribe(resp => {
                  this.roles = console.log(resp)
                  }
                );
0
import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';

import { Observable } from 'rxjs';

/** Pass untouched request through to the next request handler. */
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
      return next.handle(req);
    }
}

interceptors are capable to add token in your Header

go through URL Bellow https://angular.io/guide/http#intercepting-requests-and-responses

stealthyninja
  • 10,343
  • 11
  • 51
  • 59