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:
How can i can check the token expiry date so that if token is expired i can logout the user .
How can i maintain the token through out the application using storage right now i manually calling the constructor in the service ?
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!';
}));
}