1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

There is something wrong when requesting a new token with refresh token in Angular

Discussão em 'Angular' iniciado por serhat başoğlu, Outubro 16, 2024.

  1. The first interceptor adds the jwt to the request header.

    export const jwtInterceptor: HttpInterceptorFn = (req, next) => {
    const authService = inject(AuthService);
    const router = inject(Router);
    let authToken = localStorage.getItem("accessToken");
    const apiUrl = req.url.startsWith("https://localhost:7096/api");
    if(authToken && apiUrl){
    req = req.clone({
    setHeaders:{
    Authorization: `Bearer ${authToken}`
    }
    });
    }
    return next(req);

    };


    Second interceptor handles global errors.

    export const errorHandlerInterceptor: HttpInterceptorFn = (req, next) => {
    const alertifyService = inject(AlertifyService);
    const router:Router = inject(Router);
    const authService = inject(AuthService);
    return next(req).pipe(catchError((err) => {
    debugger;
    if(err){
    switch(err.status){
    case 401:{
    if(localStorage.getItem('accessToken') && localStorage.getItem('refreshToken')){
    debugger;
    authService.refreshAccesToken((state) =>{
    if(state){
    console.log(localStorage.getItem('accessToken'));
    }else{
    authService.logOut();
    }
    })
    }else{
    alertifyService.message("Yetkisiz erişim!!", {
    messageType:MessageType.Error,
    position:SetPosition.TopRight
    })
    router.navigate(["/"]);
    }
    break;
    }
    }
    }

    return of(err);

    }));


    };


    @Injectable({
    providedIn: 'root'
    })
    export class AuthService {

    constructor(
    private httpClient:HttpClientService,
    private jwtHelper:JwtHelperService,
    private router:Router) {
    }
    async refreshAccesToken(callbackFunc?:(state) => void){
    const refreshToken = localStorage.getItem('refreshToken');
    const response:Observable<any>= this.httpClient.post({
    controller:"auth",
    action:"LoginRefreshToken",
    }, {refreshToken: refreshToken});
    debugger;
    try{
    const tokens:TokenResponse = await firstValueFrom(response) as TokenResponse;
    if(tokens){
    localStorage.setItem('accessToken', tokens.accessToken);
    localStorage.setItem('refreshToken', tokens.refreshToken);
    }
    callbackFunc(tokens ? true: false);
    }catch{
    callbackFunc(false);
    }
    }

    addJwtBearer(req:HttpRequest<unknown>){
    debugger;
    let authToken = localStorage.getItem("accessToken");
    const apiUrl = req.url.startsWith("https://localhost:7096/api");
    if(authToken && apiUrl){
    req = req.clone({
    setHeaders:{
    Authorization: `Bearer ${authToken}`
    }
    });
    }
    return req;
    }

    logOut(){
    localStorage.removeItem('accessToken');
    localStorage.removeItem('refreshToken');
    this.router.navigate(["/"]);
    }


    }








    The problem is that after sending the request for the repeat token I can't process the previous request without getting the unauthorized error. I have to refresh the page again. This is an illogical solution.

    Continue reading...

Compartilhe esta Página