首页 > 解决方案 > 在 Angular 应用程序中存储 JWT 的标准做法是什么?

问题描述

我将评估作为工作申请的一部分。任务是创建一个 Angular 应用程序,它将使用给定的 JWT 令牌从指定的 api 获取数据。

我以前没有使用过 JWT 令牌,所以我不确定在 Angular 应用程序中处理这些令牌的最佳方法是什么。如果有什么不同,我使用的是 Angular 6。

目前,我只是在我的服务中对其进行硬编码,并将其作为请求的一部分发送到标头中。如下所示:我觉得必须有某种最佳实践来处理这个问题。有人可以分享它是如何完成的吗?

export class MyService {

  private readonly _apiPath = `https://my.address.com/api/products`;

  private readonly _headers = new HttpHeaders({
    'authorization': `Bearer andVeryLongJWTTokenHere`});

  constructor(private http: HttpClient) {
  }

  getProducts(): Observable<Product[]> {
      return this.http.get<Product[]>(`${this._apiPath}`, { headers: this._headers });
  }

}

标签: angularjwt

解决方案


这就是我所做的,我使用HttpInterceptor的自定义实现,这样,每个 HTTP 请求都会有令牌,如果有,如果没有,请求将正常继续。

import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest } from "@angular/common/http";
import { Observable } from "rxjs";
//Service where I handle the token
import { UserSettings } from "./user.settings";

@Injectable()
export class AuthInterceptor implements HttpInterceptor{

    constructor(private userSettings: UserSettings){}

    intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
        //Check if the user is authenticated, if true, append the token   
        if(this.userSettings.isAuthenticated()){
            //Get the token
            let token: string = this.userSettings.getSessionToken();
            //Clone the original request (to be able to modify it)
            let clonedReq: HttpRequest<any> = req.clone({
                setHeaders: {'Authorization':'Bearer ' + token }
            });
            //Return the cloned request with the token
            return next.handle(clonedReq);
        }
        //At this point, the user is not authenticated, so I send the original request
        else{
            return next.handle(req);
        }        
    }
}

在模块的 providers 数组中:

providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, },
],

为了存储令牌,目前我使用 LocalStorage,但我已经阅读了几篇关于不这样做的博客文章,主要是出于安全原因:

您页面上的任何 JavaScript 代码都可以访问本地存储:它没有任何数据保护。出于安全原因,这是一个大问题。这很糟糕。


推荐阅读