Search code examples
angularapioauthjwttoken

Api Request with Bearer Token in Angular


The case is to build a Login and Register page in Angular and access an api when registered and logged in. I know the concept of sending the login data to an, api getting the token back etc.

My Problem is that I don't know how to implement the workflow in Angular. The backend is written in PHP. I'm searching for a concept.

What is the best way and do I need Routeguards, Interceptor, Lokalstorage, Cookies?

To access an secure api and also being able to see api results in e.g postman with a token is my target.


Solution

  • What do you need is interceptor - it let you "intercept" all HTTP request and edit them. for example you can do this:

    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
    
    intercept(req: HttpRequest<any>, next: HttpHandler): 
      Observable<HttpEvent<any>> {
      const authToken = localstorage.getItem('token');
      const authReq = req.clone({
      headers: req.headers.set('Authorization', 'Bearer ' + authToken)
     });
    return next.handle(authReq);
    }
    }
    

    then you need to add it to your providers array:

    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
    

    to exclude /login route - you can wrap the interceptor code with if condition:

    if( !req.url.startsWith('/login') { }
    

    or you can provide this interceptor only in the other modules and not in login module (if you have any)

    good luck :)