Using SocialLoginModule for token refresh in Angular 6 with Google sign in functionality

Currently, I am in the process of developing a web application with Angular 6, incorporating Google sign-in using the SocialLogin library. Below is the code snippet that I have implemented:

public socialSignIn(socialPlatform : string) {
      let socialPlatformProvider;
      if(socialPlatform == "facebook"){
        socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID;
      }else if(socialPlatform == "google"){
        socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;
      }

      this.socialAuthService.signIn(socialPlatformProvider).then(
        (userData) => {

        let user: User = new User();
        let newuserrequest: NewUserRequest = new NewUserRequest();

        user.email = userData.email;
        var username;
        username = userData.name;
        var uuid = this.newGuid();
        newuserrequest.requestId = uuid;
        newuserrequest.user = user;
        newuserrequest.accountId = userData.id;
        newuserrequest.accountIdToken = userData.idToken;
        this.newuserrequest = Array<NewUserRequest>(newuserrequest);
        this.personname2 = userData.name;
        this.personname = this.personname2.toString();
        console.log('Personname: ' + this.personname);
        this.div = document.getElementById("name");
        this.div.textContent = this.personname;
        var token;
        token = userData.idToken;
        this.saveValueUser(username, user.email);

        this.islogedin = true;

        this.saveValue(token);
        this.communicator = new CommunicatorService(this.httpClient);
        var url;
        url = "myurl/newuser";
        this.communicator.getDataFromServer(this.newuserrequest, url)
        .subscribe(
          (data:any) => {
            console.log(data);
          }
        );
        }
      );
    }

The above code works properly, but it has a limitation as the token expires after 1 hour. To address this issue, I developed a method utilizing JWT-helper-service to check the validity and expiration time of the token. Here is the method:

  private tokenHandler(){
    this.helper = new JwtHelperService();
    this.isExpired = this.helper.isTokenExpired(this.token);
    if(this.isExpired != true) {
      this.expirationDate = this.helper.getTokenExpirationDate(this.token);
    }
    console.log("Is expired: " + this.isExpired);
    console.log("Expiration date: " + this.expirationDate);
    if(this.isExpired == true){
      this.signOut();
    }
  }

I am looking for guidance on how to implement token refreshing before it expires.

Answer №1

To enhance your code, consider incorporating a scheduled call following the initial token acquisition to establish a countdown timer and automatically renew it before expiration.

For reference, take a look at this resource https://auth0.com/docs/quickstart/spa/angular2/05-token-renewal for a practical example.

Although the example is specific to AuthO libraries, you can easily modify it to fit your token retrieval library of choice.

Furthermore, keep in mind that the angular 2 focus of the example means adjustments may be needed due to changes made by rxjs (e.g., using just `of()` instead of `observable.of()`, etc.).

If you require further assistance, feel free to reach out.

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

The issue with checkboxes in datatables causing incorrect array output

Trying to integrate a checkbox into my datatables for row selection and storing selected information in array for further processing. The datatable supports pagination and variable page lengths, but encounters an issue with the following scenario: Scenar ...

Error: Angular 2 Application lacks 'Access-Control-Allow-Origin' header

Currently, I am working on a project where I am focusing on learning and practicing Angular 2. Since I do not have a server-side setup, I am making API requests to the barchart ondemand api. I am facing an issue with CORS and I am wondering if there is a ...

Implementing Material Design in React using TypeScript

I'm currently in search of a method to implement react material design with typescript, but I've encountered some challenges. It appears that using export defaults may not be the best practice due to constraints in my tsconfig. Is there an al ...

Encountered an issue: The type 'Usersinterface' is not meeting the document constraints

Below is a screenshot displaying an error: https://i.stack.imgur.com/VYzT1.png The code for the usersinterface is as follows: export class Usersinterface { readonly username: string; readonly password: string; } Next, here is the code for users ...

Can we avoid the addition of a 'children' element by JSX comment, potentially causing issues with types?

Imagine having a third party library structured like this: declare var SomeComponentFromLibrary: React.FC<{ children?: React.ReactElement }>; Within the library's definition, children is set to be a React.ReactElement, and altering this det ...

What is preventing the union distribution from occurring with T[number] when T is an ArrayLike?

Below, in this demonstration (linked playground, I anticipate that Foo<[0, 1]> and Bar<[0, 1]> will both be resolved to 0[] | 1[] due to the distribution of unions in conditional types. However, in actuality, Foo<[0, 1]> ends up being (0 ...

Trouble with Angular custom directive functionality on input pattern

Trying to create a custom Angular directive for setting a regex pattern: import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appPasswordRegex]', }) export class PasswordRegexDirective { constructor(priva ...

Tips for safely storing data in local storage using Angular 5

How can I securely store data in local storage, such as encrypting and decrypting the local storage data to prevent manipulation by other users? If it's not possible with local storage, what are alternative methods for client-side data storage? I&apo ...

Encountering a ng-select2 error while running ng-serve in Angular version 11.2.14

Encountering an error while attempting to run ng-serve on a newly cloned repository. It worked fine on my previous device but now, with the new device, a coworker suspects that the M1 Apple Silicon is causing this error. For the full error log, visit http ...

Scrolling to the bottom of an ion-content in Ionic 4

I am currently developing a chat page with Ionic 4 and I'm attempting to implement an automatic scroll feature to the bottom of the page. However, the method I tried using doesn't seem to be working as expected: import { IonContent } from "@ioni ...

Can a npm package be created using only typescript?

I am working on a project that is specifically tailored for use with TypeScript projects, and I want the code inspection to lead to the actual lines of TypeScript code instead of a definition file. However, I am struggling to set up an npm project to achi ...

Is it possible to deploy universal apps on Firebase Hosting?

After successfully deploying my Angular 2 application to Firebase hosting, I have been pleasantly surprised by how user-friendly the setup is and how seamless the deployment process has been using CI. Currently, I am exploring the possibility of adding un ...

RxJS pipe operation ignoring observable

Currently, I am in the process of transitioning an app from Promises to RxJS and I could use some guidance on whether I am heading in the right direction. Situation: I have a ModalComponent that appears when an HTTP request is sent and disappears once the ...

Retrieving Identifiers with Typescript from an object

I'm a newcomer to Typescript and I'm looking to extract ids from an observable Here's the observable data: let myObj = [{ "id": 1, "text": "Mary" }, { "id": 2, "text": "Nancy" }, { "id": 3, "text": "Paul" }, { "id": 4, "tex ...

Managing return types in functions based on conditions

Recently, I developed a function to map links originating from a CMS. However, there are instances where the link in the CMS is optional. In such cases, I need to return null. On the other hand, when the links are mandatory, having null as a return type is ...

Guide to sorting by two parameters in Angular

Is it possible to sort an angular table by two parameters? See the example below: 1-2 1-3 1-1 2-9 2-6 2-1 The desired output should be: 1-1 1-2 1-3 2-1 2-6 2-9 this.sortedData.sortingDataAccessor = (item, property) => { if (item[property]) { re ...

The reliability of Babel's TypeScript parsing is questionable

Experimented with the Angular component code written in TypeScript by using ASTExplorer with babylon7-7.0.0-beta.12 and babelv7-7.0.0-alpha.12. It successfully parsed, transformed, and generated the expected output: import { Component, OnInit } from &apos ...

Module augmentations do not allow for exports or export assignments

import { Request as ExpressRequest, Response as ExpressResponse } from 'express'; declare module 'kvl' { export = kvl; } declare const kvl: { ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void; ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

Leverage a JavaScript library with TypeScript in Angular 2

SignalR integration in my Ionic/Angular 2 application has been a challenge. I'm creating a basic Hub setup as follows: const accessToken = authManager.getRawAccessToken(); let hubUrl = environment.baseUrl + 'messages'; if (accessToken) { ...