如何使用 angular jwt 拦截带离子存储的令牌?

How to use angular jwt to intercept token with ionic storage?

我正在从存储中获取 jwt 令牌以拦截我的离子应用程序中的 http 请求。因此,为此我编写了这个程序,但它给出了错误 "Illegal constructor" 因为我不能只初始化离子存储,但它必须通过依赖注入来初始化。我该怎么做?

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

您需要拦截每个 api 调用并需要在该 api 调用请求的 header 中附加令牌,为此您需要使用 http-intercepter

这可能对你有帮助。

https://www.djamware.com/post/5c42ca7580aca754f7a9d1e8/ionic-4-and-angular-7-tutorial-http-interceptor-example

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

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

请参阅此 link https://www.npmjs.com/package/@auth0/angular-jwt

和标题 Configuration for Ionic 2+