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

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)
Archimede_PitagoricoAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Archimede_PitagoricoAuthor Commented:
Absolutely clear; thank you very much.
Julian HansenCommented:
You are welcome.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
HTTP Protocol

From novice to tech pro — start learning today.