Issue arising from frequent refresh token expiration in Angular 8

Currently, my setup involves AWS Cognito for oauth authentication. Upon login, Cognito returns a token that needs to be refreshed every hour. I implemented logic using setTimeout to handle this token refresh every hour, but this method fails upon page refresh by the user. Is there an alternative solution available?

I attempted to use setTimeout and the interval feature from rxjs to refresh the token every hour, but encountered the same issue after a page refresh.

private async setAutoRefreshToken() {
    return interval(3500000).pipe(startWith(1), switchMap(() => this.authService.refreshToken().pipe(map(auth => {
      const data = auth.AuthenticationResult;
      return data;
    }))));
  }

Answer №1

To effectively handle token expiration, one approach is to save the token and its timestamp in the localstorage. By checking the validity of the token each time it's accessed, you can ensure it remains usable. If the token is close to expiring, a new one can be requested promptly.

To account for scenarios where the token isn't accessed for an extended period, implementing a timer that checks for expiration every 10 seconds can prevent any unexpected issues related to expired tokens.

It's worth noting that this method continues to function even after a page reload.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize Angular to initiate the transmission of attribute values upon a click event

My question may be simple, but I've been struggling to find an answer. How can I send attributes or item property bindings of an item through a click event in the best way? For example: <item class="item" [attr.data-itemid]="item.id ...

Issue with Syncfusion Grid: Unable to Display Column Data as Hyperlinks

I'm currently working on a Webapp that utilizes the Syncfusion grid to display tabular data. One of my requirements is to showcase a column's data as a clickable link and trigger a function upon user interaction. After consulting the tutorial av ...

Steps for generating a unit test for code that invokes scrollIntoView on an HTML element

I'm currently working on an Angular component where I have a method that involves scrolling through a list of elements known as "cards" based on certain criteria. Despite my efforts to write unit tests for this method using the Jasmine framework, I&ap ...

Using Angular to apply multiple ngClass directives

When dealing with 2 classes, I am only interested in enabling or using them if a specific condition is met: dealDispositionFormFields.isSubtenantTakingFullSpace === 'No' How can we create the correct syntax utilizing ngClass for this purpose? Th ...

Removing empty options from a select dropdown in Angular 9

In the process of working with Angular 9, I am currently in the process of constructing a dropdown menu that contains various options. However, I have encountered an issue where there is a blank option displayed when the page initially loads. How can I eli ...

The output of switchMap inner will generate an array similar to what forkJoin produces

I have a series of observables that need to run sequentially, with each result depending on the previous one. However, I also need all the intermediate results in an array at the end, similar to what is achieved with the use of forkJoin. Below is the curr ...

"Angular EventEmitter fails to return specified object, resulting in undefined

As I work on a school project, I've encountered a hurdle due to my lack of experience with Angular. My left-nav component includes multiple checkbox selections, and upon a user selecting one, an API call is made to retrieve all values for a specific " ...

ngx-chips paste pattern division for use in Angular

I am currently working on allowing users to paste a list separated by , ; or | using ngx-chips. The solution involves utilizing the pasteSplitPattern option - which can be set as a string or RegExp. For more information, you can visit https://github.com/ ...

Eliminate the Material Stepper heading

Is there a way to remove the header navigation from the material stepper? I've tried using the following CSS code without success: .mat-horizontal-stepper-header-container{display: none} You can view the stepper on Stackblitz by clicking this link: ...

Combining data types in TypeScript (incorporating new keys into an existing keyof type)

If I have a typescript type with keys: const anObject = {value1: '1', value2: '2', value3: '3'} type objectKeys = keyof typeof anObject and I want to add additional keys to the type without manually defining them, how can I ...

Piping in Angular 2 with injected dependencies

Is it possible to inject dependencies such as a service into Angular 2 pipes? import {Pipe, PipeTransform} from 'angular2/core'; import {MyService} from './service'; //How can I inject MyService into the pipe? @Pipe({name: 'expo ...

Properly write a function in Typescript that returns the initial property of an object

Looking for a solution to adjust the function below to match the property type: const firstProp = (object: Record<string, unknown>) => object[Object.keys(object)[0]]; Any thoughts on how to modify the function so its return type aligns with the ...

There seems to be an issue with the functionality of Angular's updateValueAndValidity() method

I am facing an issue with a simple form setup: <form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate> <input type="radio" id="enabled" formControlName="enabled" [value]="true" ...

Ways to retrieve data from ngrx and display it in a component file

I have recently incorporated the ngrx library into my project to create a more dynamic model for handling data. After setting up my actions, reducers, and effects files, everything seems to be working as intended because I can observe the populated model w ...

Double curly brace Angular expressions being repeatedly evaluated during mouse click events

Within our Angular application, the code structure is as follows: <div>{{ aGetProperty }}</div> <div>{{ aMethod() }}</div> Upon clicking anywhere on the page, these expressions are being evaluated repeatedly. For example, if there ...

Error TS2339 occurs when the property "classes" is not found in the type "PropsWithChildren"

I have encountered a typescript error while transitioning our files to typescript. As a newcomer to typescript, it has been quite challenging for me to search for solutions online. My approach is to grasp the error first before delving into finding a resol ...

Creating a JSON utility type for an already existing type, such as JSON<SomeExistingType>

Is there any tool or utility available that can accomplish this task? const foo: Foo = { ... } const bar: string = JSON.stringify(foo) const baz: JSON<Foo> = JSON.parse(foo) JSON<Foo> would essentially mirror all the properties of Foo, with th ...

The Angular factory function is throwing an error and is not recognized as a

I am in the process of developing a recipe application using Angular and I am currently working on establishing communication with backend services via HTTP. My approach has been to closely follow the documentation provided by Angular which can be found at ...

Can an enum be used to store an object?

I am trying to define an enum like: enum retailers { STOREA = { label: "Amazon", value: "amazon" }; STOREB = { label: "Walmart", value: "walmart" }; } However, I encountered the following error message: Type &ap ...

Using the hash(#) symbol in Vue 3 for routing

Even though I am using createWebHistory, my URL still contains a hash symbol like localhost/#/projects. Am I overlooking something in my code? How can I get rid of the # symbol? router const routes: Array<RouteRecordRaw> = [ { path: " ...