【问题标题】:Auth headers not set using angular-token未使用 angular-token 设置身份验证标头
【发布时间】:2020-07-08 23:09:01
【问题描述】:

我刚开始使用 angular-token 的 Angular 应用程序和使用 devise-token-auth 的 rails 后端,我在登录组件中有下一个“on-submit”:

onSubmit() {
    this.output = null;
    this.tokenService.signIn(this.signInData).subscribe(
        res => {
            console.log(res)
            this.output = res;
            this.signInForm.resetForm();
            this.router.navigate(['/products']);
        }, error => {
            this.output = error;
            this.signInForm.resetForm();
        }
    );
}

使用 Chrome 的 DevTools 检查时,登录成功,并且后端返回了我使用邮递员测试的良好凭据标头(uid、访问令牌、客户端)。问题是,在加载目标页面“产品”时,用于填充该新页面的 httpClient 调用(我将调用放在解析器中以在“产品”调用完成之前不呈现任何内容)不包括任何身份验证标头,所以当然,我得到一个 401 non-authorized 错误,因此 angular-token 似乎没有根据我使用 .signIn 方法获得的标题正确更新标题。

  • 如何确保正确发送标头?
  • 我在哪里检查他们是否真的到达订阅的“res”
    • 可以看出,我控制台记录了它,但我看不到该变量中的任何标题,尽管我在 devTools 的“网络”选项卡中看到它们。

【问题讨论】:

    标签: ruby-on-rails angular devise-token-auth angular-token


    【解决方案1】:

    原来我只需要enable headers from the back-end

    在我的特殊情况下,我只需要确保使用 CORS 初始化程序公开标头,如下所示:

    # config/initializers/cors.rb
    
     Rails.application.config.middleware.insert_before 0, Rack::Cors do
       allow do
        origins '*'
        resource '*', 
            headers: :any,
            expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
            methods: [:get, :post, :put, :patch, :delete, :options]
      end
    end
    

    我错过了“暴露”这一行:

    expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
    

    【讨论】:

      猜你喜欢
      • 2019-06-19
      • 2011-11-18
      • 2015-09-05
      • 1970-01-01
      • 2013-04-26
      • 2021-04-28
      • 2019-02-21
      • 2017-08-12
      • 2011-04-28
      相关资源
      最近更新 更多