angular - 如何使用角度 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);
}
})
);
}
}
解决方案
你必须创建一个工厂函数来实现这个
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+
推荐阅读
- javascript - NextJS/React 从复杂的 HTTP 请求负载中实现数据
- javascript - 使用 useReducer 在状态更改时不重新渲染组件功能
- python - 编写一个使用python对列表进行排序的函数
- css - box-shadow 将重叠而不是覆盖
- postgresql - INSERT 的分区表是否需要 autovacuum?
- python - 地点 关于 Pandas 多个条件
- python - 将多行合并为单行
- gitlab-ci - gitlab语法:这个配置中&default是什么意思
- c# - SAML2 SLO 与 OKTA 集成,命中格式错误的请求
- r - 在 r 中更新 mapboxer 代理