gpt4 book ai didi

angular - 当 token 在 Angular 4中过期时如何重定向到注销

转载 作者:行者123 更新时间:2023-12-03 18:35:25 25 4
gpt4 key购买 nike

我有一个 Angular 4 应用程序。我在那里使用 JWT token 进行身份验证。一切正常。但是我给 JWT token 的 token 过期时间是 1 小时。一旦 token 在服务器端过期,我想将用户从前端应用程序中注销。在节点后端,我使用 express 中间件通过检查所有请求是否包含有效 token 来处理此问题。有没有办法做到这一点?

最佳答案

您可以使用 Http 拦截器。如果有任何未经授权的 401 响应。假设您正在发送带有 header 中 token 的 http 请求。您的服务器端代码检查您的 token ,最后发现, token 无效/过期返回 401 代码,您可以将用户重定向到登录页面。并且手动传递 token 并检查所有授权/未授权的http请求是非常重复的工作,您可以通过拦截器作为http请求的委托(delegate)来完成这项常见任务。查看代码示例,您将获得解决方案。

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);
}
);
}

}

关于angular - 当 token 在 Angular 4中过期时如何重定向到注销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50266733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com