可以借助 Angular Service Worker 实现 JWT 令牌的认证和管理,但需要注意 Angular Service Worker 与浏览器原生的 Service Worker 是有所不同的。
下面是一个基于 Angular Service Worker 的 JWT 认证和管理示例:
import * as jwt from 'jsonwebtoken';
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { ServiceWorkerModule, SwUpdate } from '@angular/service-worker'; import { AppComponent } from './app.component'; import { AuthInterceptor } from './auth.interceptor';
@NgModule({ declarations: [AppComponent], imports: [ BrowserModule, HttpClientModule, ServiceWorkerModule.register('ngsw-worker.js', { enabled: true }) ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { constructor(private swUpdate: SwUpdate) { if (swUpdate.isEnabled) { swUpdate.available.subscribe(() => { if(confirm("New version available. Load New Version?")) { window.location.reload(); } }); } } }
上述示例中的 AuthInterceptor 拦截