【问题标题】:How to send Authorization header with http request from angular frontend to nestjs backend如何将带有http请求的授权标头从角度前端发送到nestjs后端
【发布时间】:2019-10-01 21:50:57
【问题描述】:

我正在尝试允许我的 Angular 客户端对我的 nestjs 后端进行身份验证,以便只允许授权用户打开 websocket。

我已按照本教程设置我的 Angular 客户端 + nestjs websocket 服务器后端:https://www.joshmorony.com/creating-a-simple-live-chat-server-with-nestjs-websockets/

它显示有一个名为 SocketIoConfig 的对象,它接受一个 url 和选项来打开到 nestjs 后端的 Web 套接字连接。据我了解,为了打开 websocket,浏览器首先发送一个 http 请求,然后如果请求成功,则会收到一个“升级到 ws”响应。我想通过将标头添加到 SocketIoConfig 对象中的选项对象来将授权标头附加到此初始 http 请求。

在客户端的 app.module.ts 我有这个来打开连接:

const config: SocketIoConfig = { url: 'http://localhost:3333', options: { }};

@NgModule({
  declarations: [AppComponent, ChatComponent],
  imports: [BrowserModule, HttpClientModule, 
SocketIoModule.forRoot(config)],
  providers: [ ChatService ],
  bootstrap: [AppComponent]
})
export class AppModule {}

我希望我可以在 options 对象中添加一个 headers 对象并将 Authorization 标头添加到其中,如下所示:

const config: SocketIoConfig = { url: 'http://localhost:3333', options: {
     headers: {
       Authorization: Bearer A8V342CsArf2
       }
    }
};

但是,当我在建立连接时打开 Chrome 网络选项卡时,我在请求标头中看不到授权标头。为什么这个标头没有附加到打开的连接请求中?

【问题讨论】:

    标签: angular authentication websocket authorization nestjs


    【解决方案1】:

    您必须使用角标头(我假设这与套接字的工作方式相同)

     headers = {
       Authorization: `Bearer ${getAccessToken()}`
     };
    
     const req = request.clone({
         url: 'http://localhost:3333',
         withCredentials: true,
         setHeaders: headers
     });
    

    【讨论】:

    • 我尝试将 withCredentials 字段和 setHeaders 字段添加到选项对象,但这似乎不起作用。 Angular 正在其他地方为我向套接字发出请求,因此我无法获取请求以克隆它并添加标头
    【解决方案2】:

    如果您的所有请求都应该针对同一个令牌进行身份验证,请考虑使用interceptor

    import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs';
    
    @Injectable()
    export class AuthTokenInterceptor implements HttpInterceptor {
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req.clone({ setHeaders: { Authorization: `Bearer 123abc` } }));
      }
    
    }
    

    您还可以通过服务获取令牌,注入到拦截器构造函数中。

    【讨论】:

      猜你喜欢
      • 2015-09-06
      • 2018-09-11
      • 2015-11-27
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2017-08-07
      相关资源
      最近更新 更多