0

I am making a post request (login).

it returns a token in the response header(Set-Auth).

How can extract and use the token in a request header?

response header

    login() {

    if (this.loginForm.invalid) {
      this.messageService.warning('You\'re missing something important', null);
      return;
    }

    this.connecting.creating = true;

    if (this.loginForm.valid) {
      console.log(this.loginForm.value);
      this.adminService.submitLogin(this.loginForm.value).subscribe(
        (data: any) => {
          this.messageService.success('Login Success', 'Success!');
          this.router.navigate(['']).then();
        },
        error => {
          this.messageService.error('Something went wrong', 'Error!');
          this.connecting.creating = false;
          this.connectingErrors.creating = true;
        }
      );
    }
  }
1

1 Answer 1

1

You need to return token inside response body. Get that value and store it inside localStorage. Then create interceptor like this..

// src/app/auth/token.interceptor.ts

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}
// src/app/app.module.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './../auth/token.interceptor';
@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }
  ]
})
export class AppModule {}

After this on every http request token will be attached on the header as Authorization...

It's dangerous to store jwt tokens in local storage so I suggest you secure cookie approach because of XSS attack.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.