How to properly deal with jwt token for logout & handling multiple urls using ionic /Angular

Viewed 322

I am trying to build a app in ionic framework using angular on below topics i am unable to apply or say i dont know exact procedure for implementing that below are my key issues:

  1. How can i can check the token expiry date so that if token is expired i can logout the user .

  2. How can i maintain the token through out the application using storage right now i manually calling the constructor in the service ?

  3. How can i toggle the url based on the token i.e if token is there i have to send x/url if token is not there i have to send y/url

what i have done

Login.page.ts

  this.Auth.authenticate(this.loginForm.value).then((res: any) => {
        this.loading = false;

        if (res.idToken.payload['cognito:groups']) {
          if (res.idToken.payload['cognito:groups'].length > 0) {
            
            admin = 'true';
          } else {
            admin = 'false';
          }
        } else {
          admin = 'false';
        }
        this.storage.set('authToken',res.accessToken.jwtToken);
        this.storage.set('isLogged',true);
        this.navCtrl.navigateBack('/tabs/tab1');
      }).catch((err => {
        this.loading = false;
        this.toastServ.showToast(err.message, 'error');
      })); 

"http.interceptor.ts"

export class HttpConfigInterceptor implements HttpInterceptor {
    token:any;

    constructor(public storage: Storage ) {
        console.log('http interceptor');
        this.storage.get('authToken').then(data => {
            this.token = data;
        });
    }


    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('intercept');
        if (this.token) {
                
                request = request.clone({ headers: request.headers.set('Authorization', this.token) });
            }
    
            if (!request.headers.has('Content-Type')) {
                request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
            }
    
            request = request.clone({ headers: request.headers.set('Accept', 'application/json') });
    
            return next.handle(request).pipe(
                map((event: HttpEvent<any>) => {
                    if (event instanceof HttpResponse) {
                    }
                    return event;
                }));
        }
    }

user.service.ts

right now i am checking the token like this

 checkUserToken(){
    this.storage.get('authToken').then(data => {
      this.url = this.url + 'someotherurl/';
      this.token = data;
     });

   }
  getLatLong(): Observable<any>{
    this.checkUserToken();
    const endPoint = this.url + 'availableData';
    return this.http.get(endPoint).pipe(map(response => {
      return response;
    }), catchError(error => {
      return 'Unable establish connection!';
    }));
   }
1 Answers

1) How can i can check the token expiry date so that if token is expired i can logout the user

When you login and as for the token, it will return the expiry data too inside the object. What you can do is to store the expiry date in the Local Storage too so you can check it and handle it. For example, you can check for the expiry date when you start the app, you will have three possibilities:

  • There is neither a token nor an expiry date (first time), so you will go to the login page.
  • The token has been expired as the expiry date is less than the current date. In this case you will need to go to the login page too to get a new one.
  • The token is valid and the expiry date is greater than the current date. You have a session so there is no need to go to the login page. You can set a timeout with the difference between the two dates and when that timeout comes, you will display a popup to the user and go to login page. For example, if the current time is 09:00 and the expiry is 09:15, you will create a timeout with 15 mins that will show a popup to user once passed.

2) How can i maintain the token through out the application using storage right now i manually calling the constructor in the service ?

You can keep it in a central singleton service that you can always get / update the token using it. You can have an init method that will be called in the App Component to initialize the above logic.

3) How can i toggle the url based on the token i.e if token is there i have to send x/url if token is not there i have to send y/url

From the above logic, you can easily differentiate between the two states. So you can choose which API you want to call easily.

Related