Angular, http request with header and token for a login form

Archimede_Pitagorico
Archimede_Pitagorico used Ask the Experts™
on
Hi all,
I am trying to create a login form in Angular 6. My test app check the data written from the current user and try to match with the data received from a remote service via http (post). This is the point: with a simple request as following, all works correctly. But what about a request also with header and token? How can I create a function with this information? Or, do you have a link with a specific tutorial for this case? Thank you very much!

PS: I almost never insert "urgent" for a request but this is really urgent!

    onlogin(): void {
    
    .get('myLink'=;
    .subscribe(data => {
        this.data = data;
        this.loading = false});
    }
    
    (....)

Open in new window


(example from official Angular 6 Book, page 157)
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
You need to create an Interceptor to do this.

Create an AuthInterceptor class that implements HttpInterceptor
Something like this
export class AuthInterceptor implements HttpInterceptor {
  
  constructor(private router:Router, private auth: AuthenticationService ) {}
 
  intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
    
    // Get the auth token from the service.
    const authToken = this.auth.getAuthorizationToken();

    // Clone the request and replace the original headers with
    // cloned headers, updated with the authorization.
    const authReq = req.clone({
      headers: req.headers.set('Authorization', 'Bearer ' + authToken),
      withCredentials: true
    });

    // send cloned request with header to the next handler.
    return next.handle(authReq).pipe(
        tap(
            (event:HttpEvent<any>) => {
                console.log('Handling event', event);
           },
           (err: any) => {
                if (err instanceof HttpErrorResponse) {
                    if (err.status === 401) {
                        this.auth.logout();
                        this.router.navigate(['/login']);
                    }
                }
                
        }))
    } 

Open in new window

In your module.ts file import your authinterceptor class and then in the providers section
providers: [
  ...
  {
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptor,
    multi: true
  }
]

Open in new window


This will intercept each HTTP request and add your Authorisation header to it.

Note: This won't work out of the box - you need to add your own AuthService to provide the token.

Lookup Interceptorss, HTTPInterceptor, Token Authentication and JWT for more information on how to do this.
Absolutely clear; thank you very much.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You are welcome.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial