当令牌在角度4中过期时如何重定向到注销 [英] How to redirect to logout when token expired in angular 4

查看:90
本文介绍了当令牌在角度4中过期时如何重定向到注销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Angle 4应用程序.我在那里使用JWT令牌进行身份验证.一切正常.但是我给JWT代币的令牌到期时间是1小时.一旦令牌在服务器端过期,我想从前端应用程序中注销用户.在节点后端,我使用express middlewere通过检查所有请求是否都包含有效令牌来解决这个问题.有没有办法做这种有角度的一面呢?

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 toke is 1 hour. i want to log the user out from the front end application once the token expired in the server side. in node backend i use express middlewere to hanndle this by checking if all the requests contain a valid token. Is there a way to do this angular side as well?

推荐答案

您可以使用Http拦截器.如果有未经授权的401响应.假设您发送的HTTP请求的标头中包含令牌.您的服务器端代码检查您的令牌,最后找出令牌是否无效/过期,返回401代码,您可以将用户重定向到登录页面.手动传递令牌并检查所有已授权/未授权的HTTP请求是非常重复的工作,拦截器可以作为HTTP请求的委托人执行此常见任务.查看将获得解决方案的代码示例.

You can use Http Interceptors. If any Unauthorized 401 response. Suppose you are sending a http request with token in header. your server side code check your token and finally find out, token is invalid/expire return 401 code and you can redirect the user to login page. and manually passing token and checking all http request authorized/unauthorized is very repeated work, this common task you can do by interceptors as delegate for http request. see the code samples you'll get your solution.

AppHttpInterceptor.ts

import { Injectable } from "@angular/core";
import {
    HttpInterceptor,
    HttpRequest,
    HttpResponse,
    HttpErrorResponse,
    HttpHandler,
    HttpEvent
} from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Router } from '@angular/router'


@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {
    constructor(private router: Router){

    }
    headers = new Headers({
        'Content-Type': 'application/json',
        'Token': localStorage.getItem("Token")
    });
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        console.log("intercepted request ... ");

        // Clone the request to add the new header.
        const authReq = req.clone({ headers: req.headers.set("Token", localStorage.getItem("Token")) });

        console.log("Sending request with new header now ...");

        //send the newly created request
        return next.handle(authReq)
            .catch(err => {
                // onError
                console.log(err);
                if (err instanceof HttpErrorResponse) {
                    console.log(err.status);
                    console.log(err.statusText);
                    if (err.status === 401) {
                        window.location.href = "/login";
                    }
                }
                return Observable.throw(err);
            }) as any;
    }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { HttpClient } from "@angular/common/http";
import { FormsModule } from '@angular/forms';
import { ToasterModule, ToasterService } from "angular2-toaster";
import { BrowserAnimationsModule } from '@angular/platform-browser /animations';
import { RouterModule } from '@angular/router';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http';
import {AppHttpInterceptor} from './Common/AuthInterceptor';
import { AppRoutes } from '../app/Common/Routes';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule, HttpModule,HttpClientModule, ReactiveFormsModule, FormsModule, BrowserAnimationsModule, RouterModule.forRoot(AppRoutes)
  ],
 providers: [
 {
   provide: HTTP_INTERCEPTORS,
   useClass: AppHttpInterceptor,
   multi: true
 }
],
bootstrap: [AppComponent]
})
export class AppModule { 
  constructor(private httpClient: HttpClient){
    this.httpClient.get("https://jsonplaceholder.typicode.com/users").subscribe(
  success => {
    console.log("Successfully Completed");
    console.log(success);
  }
  );
 }

}

这篇关于当令牌在角度4中过期时如何重定向到注销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆