我有一个角度4的应用程序。我使用JWT令牌进行身份验证。一切正常。但是我给JWT toke的令牌到期时间是1小时。我想在服务器端的令牌过期后将用户从前端应用程序中注销。在节点后端我通过检查所有请求是否包含有效令牌来使用express middlewere来处理这个问题。还有办法做这个角度方面吗?
答案 0 :(得分:2)
您可以使用Http拦截器。如果有任何未经授权的401响应。假设您在标头中发送带有令牌的http请求。您的服务器端代码检查您的令牌,最后找出,令牌无效/过期返回401代码,您可以将用户重定向到登录页面。并且手动传递令牌并检查所有http请求授权/未授权是非常重复的工作,这个常见的任务你可以通过拦截器作为http请求的委托。查看代码示例,您将获得解决方案。
<强> 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);
}
);
}
}
答案 1 :(得分:1)
您可以检查令牌是否已过期,作为回复,您可以重定向到登录页面 将令牌存储在本地存储中 例如
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});
}
因此它将响应401错误,您可以通过重定向到您的登录页面来处理此问题
如果您有任何疑问,可以在评论中提问,以便我帮助您
你也可以在你的方法中使用if-else
您可以在onIt()
方法
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;
}
}
答案 2 :(得分:0)
angular2-jwt中有tokenNotExpired方法,您可以使用它来检查令牌到期
试试这个
authHttpGet(URL: string): Observable<any> {
if (!tokenNotExpired('id_token')) {
this._route.navigate(['login']);
}
}