Home > Net >  Api Request with Bearer Token in Angular
Api Request with Bearer Token in Angular

Time:12-20

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.

CodePudding user response:

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 :)

CodePudding user response:

I created a service for API and I use it to call the API. if you have a refresh token, you can develop this function.

post<T>(url: string, payload: T, needAuth: boolean = false): any {

   if (needAuth) {
     this.httpOptions.headers = this.httpOptions.headers.set('Authorization', 'Bearer '   this.tokenService.getAccessToken());
   }

   return this.httpClient.post<T>((this.serverURL)   url, payload, this.httpOptions)
   .pipe(
      map((res: any) => {
      return res.body;
      })
   );
}
  • Related