首页 文章

通过Angular 4拦截器 - Node.js发送时没有找到授权标头

提问于
浏览
0

我正在使用登录构建应用程序 .

用户可以登录并将令牌返回到前端 .

当我将令牌发送回服务器进行验证时,问题就出现了 .

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

当我登录控制台时:

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

但是,当登录快速中间件时, Headers 显示正常

console.log(req.headers.authorization);

我得 undefined

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

enter image description here

拦截器:

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'
    });
  }
})

3 回答

  • 0

    默认情况下隐藏Authorization-header . 在你的后端你需要公开 Headers :

    Access-Control-Expose-Headers: Authorization
    

    请参阅此主题作为参考:

    Angular 2: Get Authorization header

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

    console.log(req.headers.authorization);
    

    不应该这样

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

    代替?

  • 0

    以下是有关如何实施可能有助于您的案例的拦截器的一些评论:

    1) Interceptors require angular version 4.3 || >

    2) Remember to provide the interceptor in our main 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) In your service that reaches the endpoint, make sure to add the new http client:

    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) Also, edit your interceptor code and add 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);
        }
    

    如果您已按照此步骤操作但未显示 Headers ,请粘贴服务和模块代码

  • 0

    使用tymon / jwt laravel包进行角度5和laravel 5后端处理令牌认证时也会遇到同样的问题 .

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

    当我将任何一个改为正确的http动词(get,post ...)时,问题就消失了:Route :: get(...)

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

相关问题