【问题标题】:No Authorization header found when being sent via Angular 4 interceptor - Node.js通过 Angular 4 拦截器发送时未找到授权标头 - Node.js
【发布时间】:2018-04-09 03:25:59
【问题描述】:

我正在使用 login 构建一个应用程序。

用户可以登录,一个token返回给前端。

问题是在我将令牌发送回服务器进行验证时发生的。

我正在使用 HttpInterceptor 将 Authorization 标头发送到服务器。

当我登录控制台时:

  console.log(cloned.headers.get("Authorization"))

但是,当登录到 express 中间件时,标题显示正常

console.log(req.headers.authorization);

我收到undefined

下面还有来自网络选项卡的请求标头,如您所见,没有授权

拦截器:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const id_token = localStorage.getItem("id_token");

    if (id_token) {
      const cloned = req.clone({
        headers: req.headers.set("Authorization", "Bearer " + id_token)
      });
      // console.log(cloned)
      console.log(cloned.headers.get("Authorization"))
      return next.handle(cloned);
    }
    else {
      return next.handle(req);
    }
  }
}

表达:

router.use('/edit', function(req, res, next) {
  console.log(req.headers.authorization);
  const checkIfAuthenticated = expressJwt({
    secret: RSA_PUBLIC_KEY
  });

  if (checkIfAuthenticated) {
    return res.status(401).json({
      title: 'Not Authorised',
      error: 'You are not authorised'
    });
  }
})

【问题讨论】:

    标签: node.js angular express


    【解决方案1】:

    使用 tymon/jwt laravel 包处理令牌身份验证的 angular 5 和 laravel 5 后端存在相同的问题。

    我的问题来自后端。在我的 api 路线中,我使用: 路线::any(...)

    当我将 any 更改为正确的 http 动词(get,post...)时,问题就消失了: 路线::get(...)

    当我在 chrome 中检查网络面板时,对后端的请求被发送了两次,第一次没有令牌,另一个有令牌

    【讨论】:

      【解决方案2】:

      以下是一些有关如何实现拦截器的 cmets,它们可能会对您的情况有所帮助:

      1) 拦截器需要 Angular 4.3 版本 || >

      2) 记得在我们的主 app.module 中提供拦截器:

      /** Interceptors */
      import {HttpClientModule, HTTP_INTERCEPTORS} from '@angular/common/http'; <-- notice the common in @angular/common/http 
      import {TokenInterceptor} from './path/to/TokenInterceptor ';
      
      @NgModule({
        imports: [
          ...
          HttpClientModule
        ],
        providers: [
          {provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true}
        ],
        bootstrap: [AppComponent]
      })
      export class AppModule { }
      

      3) 在到达端点的服务中,确保添加新的 http 客户端:

      import {HttpClient} from '@angular/common/http'; <-- Super important to include new HttpClient from @angular/common/http instead of old http from @angular/http...
      
      @Injectable()
      export class MyService {
      
          constructor(private http: HttpClient ) { }
      // your GET POST and other requests made with http will now have the desired header...
      

      4) 另外,编辑您的拦截器代码并添加setHeaders:

       intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
          const id_token = localStorage.getItem("id_token");
      
          if (id_token) {
             req = req.clone({
                setHeaders: {
                   Authorization: `Bearer ${id_token}`
                }
             });
             return next.handle(req);
          }
      

      如果您已经按照此步骤操作,但您的标题没有出现,请粘贴您的服务和模块代码

      【讨论】:

        【解决方案3】:

        默认情况下,Authorization-header 是隐藏的。 在您的后端,您需要公开标头:

        Access-Control-Expose-Headers: Authorization
        

        请将此线程作为参考:

        Angular 2: Get Authorization header

        @更新: 对不起,误解了你的问题。 请重新检查您的第二个 console.log()。您正在登录:

        console.log(req.headers.authorization);
        

        不应该是这样的

        console.log(req.headers.get("Authorization"));
        

        改为?

        【讨论】:

        • 谢谢,试过了,还是不行,那不就是为了让前端读取返回的headers吗?我的问题是没有得到标头服务器端
        • 抱歉,误解了您的问题。请在答案中查看我的更新。
        猜你喜欢
        • 2018-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-20
        • 2020-10-23
        • 2023-02-23
        • 1970-01-01
        相关资源
        最近更新 更多