How to redirect to logout when token expired in angular 4

后端 未结 3 2151
北荒
北荒 2021-02-09 06:26

I have a angular 4 application. There i use JWT token for authentication purposes. Everything works fine. but the token expiration time i have given to the JWT token is 1 hour.

3条回答
  •  旧巷少年郎
    2021-02-09 07:18

    you can check if the token is expired or not and as a response, you can redirect to login page store token in local storage for example

     yourmthod(parametr) {
            this.token = localStorage.getItem("token");
            this.headers = new Headers();
            this.headers.delete(this.token);
            this.headers.append("Authorization", this.token);
            return this._http.post(Constants.SERVER_URL + 'your method', {headers: this.headers});
        }
    

    so it will response 401 error and you can handle this by redirecting to your login page

    if any query you can ask a question in comments so I can help you

    and you can also use if-else in your method

    and you can write code in app.component.ts in onIt() method

    ngOnInit(): void {
            let token = localStorage.getItem("token");
            if (token) {
                this.isTokenAvaialable = true;
                this.http.get(Constants.SERVER_URL + 'your mthod to validate token' + token).subscribe(data => {
                    if (data == true) {
                        if (window.location.pathname == "") {
                            this.router.navigate(['/home', {outlets: {'r2': ['dashboard']}}]);
                        }
                    } else if (data == false) {
    
                        this.logout('Server restarted.Please login again!!');
                    } else {
    
                        this.logout('Session expired.Please login again.!!');
                    }
    
                }, (err: HttpErrorResponse) => {
                    this.toastr.warning('Server restarted.Please login again!!', 'Alert');
                    localStorage.removeItem("token");
                    this.isTokenAvaialable = false;
                    this.logout('Server restarted.Please login again!!');
                });
            } else {
                this.isTokenAvaialable = false;
                this.router.navigate(['']);
                localStorage.removeItem("token");
                this.isTokenAvaialable = false;
            }
        }
    

提交回复
热议问题