【问题标题】:How to set HTTP only cookie in NestJS如何在 NestJS 中设置仅 HTTP cookie
【发布时间】:2021-05-26 12:19:23
【问题描述】:

我正在尝试使用 accessToken 和 refreshToken 实现 JWT 授权。 accessToken 和 refresh token 都需要在 HTTP only cookie 中设置。

我试过这段代码,但它没有设置 cookie。我在这里使用的是 NestJS 框架。

import { Controller, Request, Post, Body, Response } from '@nestjs/common';
@Controller()
export class UserController {
  constructor() {}

  @Post('users/login')
  async login(
    @Request() req,
    @Body() credentials: { username: string; password: string },
    @Response() res,
  ) {
    try {
      // Login with username and password
      const accessToken = 'something';
      const refreshToken = 'something';
      const user = { username: credentials.username };

      res.cookie('accessToken', accessToken, {
        expires: new Date(new Date().getTime() + 30 * 1000),
        sameSite: 'strict',
        httpOnly: true,
      });
      return res.send(user);
    } catch (error) {
      throw error;
    }
  }
}

res.send() 方法运行良好,我正在获取数据作为响应。如何在此处设置 cookie?

这是我的 main.ts 文件:-

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger } from '@nestjs/common';
import { AuthenticatedSocketIoAdapter } from './chat/authchat.adapter';
import * as cookieParser from 'cookie-parser';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  app.use(cookieParser());
  app.useWebSocketAdapter(new AuthenticatedSocketIoAdapter(app));
  await app.listen(3000);
  Logger.log('User microservice running');
}
bootstrap();

并获取它正在使用的 cookie:-

request.cookies

【问题讨论】:

  • 您如何检查 cookie?这段代码对我来说很好
  • 我正在使用 cookie 解析器,然后尝试通过以下方式获取 cookie:-request.cookies
  • 您是否设置了 cookie 的域?看起来你不是,所以它可能默认使用那条路线并且只有那条路线。您如何在客户端/调用方检查 cookie?
  • 如何从客户端发送请求?听起来服务器端正在设置 cookie,现在是从客户端(浏览器)发送 cookie 的问题
  • 我相信Axios需要你添加withCredentials才能在请求中添加cookies。如果您可以显示客户端代码会有所帮助

标签: typescript express cookies jwt nestjs


【解决方案1】:

cmets 中的对话:

在客户端,Axios 需要将 withCredentials 设置为 true 才能将 cookie 发送回服务器。服务器正在按预期发送和设置 cookie。

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 2016-12-28
    • 2020-11-21
    • 2011-10-05
    • 1970-01-01
    • 2011-06-24
    • 2019-09-24
    • 1970-01-01
    • 2015-02-08
    相关资源
    最近更新 更多