简体   繁体   English

将身份验证令牌传递给自定义 Angular 7 库

[英]Passing authentication token to custom Angular 7 library

I need to create a custom Angular 7 library that is able to take in an authorization token from its application so it can use the same authorization token as the rest of the application to access certain APIs.我需要创建一个自定义 Angular 7 库,它能够从其应用程序中获取授权令牌,以便它可以使用与应用程序其余部分相同的授权令牌来访问某些 API。 I looked into injecting the authorization token through the library's forRoot() in the app.module.ts, but the authorization token is not available when the app is bootstrapped.我研究了通过 app.module.ts 中库的 forRoot() 注入授权令牌,但是当应用程序启动时授权令牌不可用。

Are there any suggestions on how to accomplish this?有没有关于如何实现这一点的建议? In short, I need a way for the custom library to take in an authorization token so that is ready whenever the API is used during runtime.简而言之,我需要一种让自定义库接收授权令牌的方法,以便在运行时使用 API 时随时可用。

In my angular application, I simply use an interceptor to read the JWT token and use it on HTTP/HTTPS request.在我的 angular 应用程序中,我只是使用拦截器来读取 JWT 令牌并在 HTTP/HTTPS 请求上使用它。

import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';

import {Observable} from 'rxjs';
import {AuthService} from '../services/auth.service';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    constructor(public service: AuthService) {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        if (this.service.isAuthenticated()) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${this.service.token}`
                }
            });
        }
        return next.handle(request);
    }
}

I also define the root module in this way:我也以这种方式定义了根模块:

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...

    AppRoutingModule,
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }
  ]
  ,
  bootstrap: [AppComponent]
})
export class AppModule {
}

The token is taken at runtime from the service injected in the interceptor.令牌在运行时从拦截器中注入的服务中获取。 If you need to consult the entire project, you can find it on github .如果需要查阅整个项目,可以在github上找到。

A possible solution is to delegate at the application interceptor definition the capability to retrieve the JWT token.一种可能的解决方案是在应用程序拦截器定义处委托检索 JWT 令牌的功能。 In this way, all the application calls will be managed in the same way.这样,所有的应用程序调用都将以相同的方式进行管理。

Hope this helps.希望这可以帮助。

one possible solution may achieved by using localStorage一种可能的解决方案可以通过使用localStorage来实现
by make an agreement on same keyName between angular-app and custom-library which is nice if the user of the library can customize it.通过在 angular-app 和 custom-library 之间就相同的keyName达成协议,如果库的用户可以自定义它,这很好。

localStorage.setItem('apiData', JSON.stringify(apiDataObject));

const apiDataObject = JSON.parse(localStorage.getItem('apiData'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM