JHipster:在向微服务进行API调用时接收401 Unauthorized

时间:2017-08-24 13:18:31

标签: angular lazy-loading axon

我目前正在使用Jhipster生成以下组件:

  • UAA - Auth Server
  • API网关
  • 微服务 - 产品1
  • 服务发现 - 领事

其他组成部分:

  • 自定义前端(Angular 4) - 在一个单独的项目中

另外需要注意的是,自定义前端使用的是Jhipster angular 4代码,可以在vanilla Jhipster Api Gateway中找到。 这包括customHttpProvider。

所包含的课程如下图所示: enter image description here

目前我可以使用此设置成功登录并在UAA上调用API,但是,当我尝试拨打产品上的任何APIS时,我会收到 401 Unauthorized ,例如发布到 Product1 / api / zcd

Consul中的服务都是可见的绿色,Gateway也将UAA和Product1作为注册和可用路线。

enter image description here

到目前为止,我发现当我对Product进行api调用时,似乎没有调用AuthInterceptor。 我尝试手动将jwt令牌附加到方法,这解决了问题,但我不明白为什么customHttpProvider不被用于拦截请求和附加令牌。

如下所示,当我手动插入令牌时,我的ProductService工作正常,但这显然不是正确的方法。

@Injectable()
export class ProductService {

    private options = new Headers();

    constructor(private http: Http) {
        this.options.append('Authorization', 'Bearer ' + 'token is inserted here');
    }

    priceProduct(productPriceRequest: productPriceRequest): Observable<IdResponse> {
        return this.http.post('Product1/api/zcd', productPriceRequest, { headers: this.options })
            .map(response => response.json());
    }
}

1 个答案:

答案 0 :(得分:2)

<强>解决:

有两件事给我造成了问题。 需要注意的是,它们与JHipster没有直接联系,而是与Jhipster集成的问题:

问题:

  1. Axon 3
  2. 具有延迟加载模块的自定义Angular 4前端。
  3. <强>解决方案:

      • 我已将axon 3纳入产品微服务并作为其中的一部分 轴突配置,它初始化一个令牌存储(没有任何东西 做安全)。
      • MicroserviceSecurityConfiguration中的tokenStore bean被认为是JwtTokenStore类型被覆盖为 InMemoryTokenStore。
      • 解决方案是将MicroserviceSecurityConfiguration中的tokenStore bean重命名为jwtTokenStore。
      • 我有很多延迟加载的模块。根据这种情况下的文档,有一个SharedServiceModule使用forRoot()并在AppModule中导入。
      • 但是当我有一个服务.e.g在ProductModule中导入的ProductService时,它覆盖了在SharedServiceModule中导入的Http Factory(在AppModule中导入Http Factory时的行为相同)。
      • 解决方案是创建一个与customHttpProvider函数(在SharedServiceModule中)相同级别提供的HttpProviderService。然后,它为应用程序中较低级别的所有其他服务管理Http。 SharedServiceModule HttpProviderService