Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 Add Token to header before posting with httpClient

I am using a restapi and it requires that I add a token to the header before I can create a new record.

Right now I have a service to create a new record which looks like this:

service.ts

create(title, text) {
    let headers: HttpHeaders = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    headers = headers.append('Authorization', token); // Not added yet as this is the reason for the question
    return this.http.post('http://myapi/api.php/posts', {
      title: 'added title',
      text: 'added text'
    }, { headers });
  }

app.component.ts

add() {
    this.service.create('my title', 'body text').subscribe(result => {
      console.log(result);
    });
  }

The problem with this is that it won't let me add the new record because it requires a token and in order to get a token I need to run this:

getToken() {
    let headers: HttpHeaders = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    return this.http.post('http://myapi/api.php/user', {
      username: 'admin',
      password: 'password'
    }, { headers });
  }

My question is...How do I get this two together into one call instead of two...or when is the best way to do this?


1 Answers

Apart from what @Pardeep Jain already mentioned, you can add an interceptor (> Angular version 4, you mentioned you're using 5) for your HttpClient that will automatically add Authorization headers for all requests.

If you need top be authenticated for only one request, it's better to keep things simple and use Pardeep's solution.

If you want to be authenticated for most of your requests, then add an interceptor.

module, let's say app.module.ts

@NgModule({
 //...
 providers: [
    //...
    {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtInterceptor,
      multi: true
    },
    //...
    ]
//...
})

and your jwt interceptor, let's say jwt.interceptor.ts

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor(private injector: Injector, private router: Router) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {  
    const authReq = req.clone({
      headers: req.headers.set('Authorization', /* here you fetch your jwt */this.getToken())
        .append('Access-Control-Allow-Origin', '*')
    }); 
    return next.handle(authReq).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response if you want
      }
    }, (response: HttpErrorResponse) => { });
  }

  getToken() {
    let headers: HttpHeaders = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    return this.http.post('http://myapi/api.php/user', {
      username: 'admin',
      password: 'password'
    }, { headers });
  }
}

If you want to read something, more here: https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8

like image 51
Razvan Dumitru Avatar answered Jan 30 '26 13:01

Razvan Dumitru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!