0

So, I am currently in progress with a project that I want to do and it is basically a food shop project. The thing is that I have user that will add products to his/her cart and buy them. Also I have an admin which will be adding/removing/changing products/users. So the main thing is that when I test the API in postman - it works with no problem the problem I think is in the front-end, because when I open the console in google it shows 401 error. Here is the code of my interceptor and guard. And also the authentication is made with roles(user/admin).

interceptor:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from "@angular/core";
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(private router: Router) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (localStorage.getItem('token') !== null) {
            let request = req.clone({
                headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('token'))
            })

            return next.handle(request).pipe(
                tap(
                    success => { },
                    error => {
                        if (error.status == 401) {
                            localStorage.clear()
                            this.router.navigateByUrl('/home')
                        } else {
                            localStorage.setItem('error', error)
                        }
                    }
                )
            )
        } else {
            return next.handle(req.clone())
        }
    }
}

guard:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private router: Router) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (localStorage.getItem('token') !== null) {
      return true
    } else {
      this.router.navigateByUrl('/home')
      return false
    }
  }

}

2
  • We need to see your API code Too, because the error is coming from the server. Commented Jan 17, 2021 at 18:01
  • As I said it is working fine when testing in Postman. Commented Jan 18, 2021 at 13:45

1 Answer 1

1

If your api is working well with postman you should kinda copy the request with the same authorization headers, maybe you are not passing the token correctly or even generating it. You can try a request something like this.

return this.http.get<Something[]>(url, {
      headers: new HttpHeaders().set('Authorization',
        `bearer ${access_token}`).set('Content-Type', 'application/json')
    });
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! This worked, maybe there is a problem in passing the token because when I type console.log(localStorage.getItem('token')) the token is displayed in the console and exists but still I could not figure it out. Much appreciated! :)
maybe parse the token like this let tk = JSON.parse(sessionStorage.getItem('token'));
I'll try this as well but it is working for now. Thanks!

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.