首页 > 解决方案 > 如何使用角度 jwt 来拦截具有离子存储的令牌?

问题描述

我正在从存储中获取 jwt 令牌,以拦截我的 ionic 应用程序中的 http 请求。所以为此我编写了这个程序,但它给出了错误“非法构造函数”,因为我不能只初始化离子存储,但它必须通过依赖注入进行初始化。我怎样才能做到这一点?

import { IonicModule, IonicRouteStrategy } from '@ionic/angular'    
import { HttpClientModule} from '@angular/common/http';
import { JwtInterceptor } from './auth/interceptors/jwt.interceptor';
import { JwtModule } from '@auth0/angular-jwt';
import { Storage } from '@ionic/storage'


function tokenGetter(): Promise<string>{
  const storage = new Storage();**//Error: illgeal constructor**
  return this.storage.get("ACCESS_TOKEN");
}  

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule,
    JwtModule.forRoot({
      config: {
        tokenGetter: (() => tokenGetter()),
        whitelistedDomains: ['localhost'],
        blacklistedRoutes: ['example.com/examplebadroute/']
      }
    })
  ],
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    ErrorInterceptor, JwtInterceptor
  ],
  bootstrap: [AppComponent]
})

export class AppModule {
}

这就是我保存令牌的方式,

export class AuthService {

  constructor(private httpClient: HttpClient, private storage: Storage) {
  }

  login(email: string, password: string){

    const data = {
      password: password,
      email: email,
    }

    return this.httpClient.post(LOGIN_URL, data).pipe(
      tap(async (res: IAuthResponse) => {
          const token = res.data.token;
          this.storage.set("ACCESS_TOKEN", token);
        }
      })
    );
  }
}

标签: angularionic4

解决方案


你必须创建一个工厂函数来实现这个

export function jwtOptionsFactory(storage) {
  return {
    tokenGetter: () => {
      return storage.get("ACCESS_TOKEN");
    },
    whitelistedDomains: ['localhost'],
    blacklistedRoutes: ['example.com/examplebadroute/']
  }
}

在您的模块中,您必须像这样进行更改

import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt';
import { Storage } from '...'

然后

JwtModule.forRoot({
  jwtOptionsProvider: {
    provide: JWT_OPTIONS,
    useFactory: jwtOptionsFactory,
    deps: [Storage]
  }
})

有关参考,请参阅此链接https://www.npmjs.com/package/@auth0/angular-jwt

和标题Configuration for Ionic 2+


推荐阅读