【问题标题】:Angular2 jwt auth via interceptor in submoduleAngular2 jwt auth 通过子模块中的拦截器
【发布时间】:2020-04-11 11:51:01
【问题描述】:

我有一个应用程序,其中包含多个模块,遵循post 中建议的架构。我需要知道拦截器的项目文件夹结构中的正确配置和定位,以便使用@auth0/angular-jwt 库以及模块导入结构附加带有承载令牌的授权标头。我有一个核心模块分解通用模块导入,但我想将此自动化的特定功能限制为我的自定义业务逻辑模块。提前致谢。

【问题讨论】:

  • 子模块是否包含任何组件?示例:登录组件.ts
  • 是的,也是与我的api中所有auth端点相关的服务
  • 这是一个延迟加载的模块,对吧?
  • 不,不是,但如果能知道这种情况下的处理方法也很好
  • 我不想在应用模块中出现与身份验证相关的混合代码。目前我在 app 模块的提供者中有拦截器,以及导入中的JwtModule.forRoot ...

标签: angular jwt-auth


【解决方案1】:

此配置必须在 app.module.ts 文件中。例如:

// other imports...
import { JwtModule } from '@auth0/angular-jwt';

export function tokenGetter(): string {
    return localStorage.getItem('token');
}

@NgModule({
  declarations: [
    // your declarations...
  ],
  imports: [
    // your imports...
    JwtModule.forRoot({
        config: {
            tokenGetter: tokenGetter,
            whitelistedDomains: ['localhost:5000'],
            blacklistedRoutes: ['localhost:5000/api/auth']
        }
    }),
  ],
  providers: [
    // your providers...
  ],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule { }

【讨论】:

  • app.module.ts 通常用于根级模块配置,在我的应用程序的特定情况下,身份验证功能不是根级功能。我想将此功能仅限于子模块,例如“身份验证模块”。
【解决方案2】:

如果您的项目中有延迟加载的模块。 那么你可以使用 auth0/angular-jwt 库的 disallowedRoutes 功能

disallowedRoutes

如果您不想替换特定路由的授权标头,请将它们列在 disallowedRoutes 中。如果您的初始身份验证路由位于允许的域上并采用基本身份验证标头,这将很有用。这些路由需要使用正确的协议(Http://、https://)作为前缀。如果您想将路由添加到不允许的路由列表而不考虑协议,您可以在其前面加上 //。

JwtModule.forRoot({
  config: {
    // ...
    disallowedRoutes: [
      "http://localhost:3001/auth/",
      "https://foo1.com/bar/",
      "//foo1.com/bar/baz",
      /localhost:3001\/foo\/far.*/,
    ], // strings and regular expressions
  },
});

【讨论】:

  • 我正在寻找一种配置,其中我不必在应用程序模块中包含安全功能的代码,我想知道是否可以将其包含在子模块中,使维护更可行
【解决方案3】:
import { ModuleWithProviders, NgModule } from '@angular/core';
import { LoadingComponent } from '../components/home/shared/loading/loading.component';
import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt';
import { JwtService } from '../util';


export function jwtOptionsFactory(jwtService: JwtService) {
  return {
    tokenGetter: () => {
      return jwtService.getToken();
    }
  };
}

@NgModule({
  imports: [
    JwtModule.forRoot({
      jwtOptionsProvider: {
        provide: JWT_OPTIONS,
        useFactory: jwtOptionsFactory,
        deps: [JwtService]
      }
    })
  ],
  declarations: [LoadingComponent],
  exports: [JwtModule],
})
export class AuthModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: AuthModule
    };
  }
}

AuthModule.forRoot() 添加到 app.module.ts 的导入中

【讨论】:

    猜你喜欢
    • 2018-07-23
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 2016-06-28
    • 2019-04-17
    相关资源
    最近更新 更多