API request fails with 500 error and loops infinitely

Discussão em 'Angular' iniciado por Zed, Dezembro 3, 2024.

  1. Zed

    Zed Guest

    I have an Angular application with the following features:

    • A login method that retrieves an access token.
    • A getRefreshToken method that retrieves a refresh token.
    • A JwtInterceptor that:
      • Adds the token to the requests.
      • If a tokenInvalid error occurs, triggers another interceptor to call the getRefreshToken method.

    Problem:
    When the API is not running, the application continuously tries to call the getRefreshToken method in a loop to obtain a new refresh token, and I don’t understand why.

    AuthenticationInfrastructure :

    private auth$: Observable<AuthenticationToken> | null | undefined;

    login(email: string, password: string): Observable<AuthenticationToken> {
    if (!this.auth$) {
    const body = new HttpParams()
    .set('username', email)
    .set('password', password);

    const headers = new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded',
    });

    this.auth$ = this.httpClient
    .post<AuthenticationToken>(
    'http://localhost:8080/realms/master/protocol/openid-connect/token/',
    body.toString(),
    { headers }
    )
    .pipe(shareReplay(1));
    }
    return this.auth$;
    }

    refreshToken() {
    return from(this.storage.get('refresh_token')).pipe(
    switchMap((storedRefreshToken) => {
    const body = new HttpParams()
    .set('grant_type', 'refresh_token')
    .set('refresh_token', storedRefreshToken);

    const headers = new HttpHeaders().set(
    'Content-Type',
    'application/x-www-form-urlencoded'
    );

    return this.httpClient
    .post<AuthenticationToken>(
    'http://localhost:8080/master/clovis/protocol/openid-connect/token/',
    body,
    { headers }
    )
    .pipe(shareReplay(1));
    })
    );
    }


    JwtInterceptor :

    export function jwtInterceptor(request: HttpRequest<any>, next: HttpHandlerFn) {
    const storage = inject(Storage);

    return from(storage.get('access_token')).pipe(
    switchMap((token) => {
    const newRequest = request.clone({
    setHeaders: {
    Authorization: 'Bearer ' + token,
    },
    });
    return next(newRequest);
    })
    );
    }

    export const refreshInterceptor: HttpInterceptorFn = (req, next) => {
    const authInfra = inject(AuthenticationInfrastructure);
    const localStorage = inject(LocalStorageAuthenticationInfrastructure);
    const authApp = inject(AuthenticationApplication);

    return next(req).pipe(
    catchError((error: HttpErrorResponse) => {
    if (error.status === 401 || error.status === 0) {
    return authInfra.refreshToken().pipe(
    switchMap((tokenResponse: WithToken) => {
    localStorage.startSession({
    access_token: tokenResponse.access_token,
    refresh_token: tokenResponse.refresh_token,
    });
    const newAuthReq = req.clone({
    headers: req.headers.set(
    'Authorization',
    `Bearer ${tokenResponse.access_token}`
    ),
    });
    return next(newAuthReq);
    }),
    catchError((refreshError) => {
    console.error('Error refreshing token', refreshError);
    authApp.logout();
    return throwError(() => new Error('Token refresh failed!'));
    })
    );
    } else {
    return throwError(() => error);
    }
    })
    );
    };


    My Browser Consol :

    user.application.ts:12
    POST http://localhost:8080/master/clovis/protocol/openid-connect/token/ net::ERR_CONNECTION_REFUSED
    user.application.ts:12
    POST http://localhost:8080/master/clovis/protocol/openid-connect/token/ net::ERR_CONNECTION_REFUSED
    user.application.ts:12
    POST http://localhost:8080/master/clovis/protocol/openid-connect/token/ net::ERR_CONNECTION_REFUSED
    user.application.ts:12
    POST http://localhost:8080/master/clovis/protocol/openid-connect/token/ net::ERR_CONNECTION_REFUSED
    user.application.ts:12
    POST http://localhost:8080/master/clovis/protocol/openid-connect/token/ net::ERR_CONNECTION_REFUSED
    user.application.ts:12
    POST http://localhost:8080/master/clovis/protocol/openid-connect/token/ net::ERR_CONNECTION_REFUSED

    Continue reading...

Compartilhe esta Página