Reputation: 167
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
}
}
}
Upvotes: 0
Views: 98
Reputation: 64
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')
});
Upvotes: 1