0

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.

2 Answers 2

1

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

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

4 Comments

that's an excellent idea for a set token but when you call public API, the token is assigned to a header. for example : login api
Is it possible to use interceptor with header instead of local storage?
what do you mean? it's usually stored in localStorage so we need to take it from there and add it to the header of the outgoing request ( as I did )
The header is set in php. I'm searching for a get request to access the api.
0

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;
      })
   );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.