与JWT Guard一起测试E2E

发布于 2025-01-25 00:30:37 字数 2221 浏览 3 评论 0原文

我正在尝试将E2E测试用于此用户更新功能。当用户登录其ID和电子邮件中时,将其保存到JWT令牌中并存储在Httponly Cookie中。我的问题是如何获取这个令牌,以使其通过JWT Guard,从JWT令牌获得ID并更新正确的用户。因为目前,我显然会得到未经授权的消息。

user.2e2-spec.ts

const mockUser: UpdateUserDto = {
  email: '[email protected]',
  first_name: 'first_name1',
  last_name: 'last_name1',
  password: 'password1',
};

const mockLoginUser: LoginUserDto = {
  email: '[email protected]',
  password: 'password',
};

describe('Auth controller (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('should update user info', async () => {
    const loginRes = await request(app.getHttpServer())
      .post('/login')
      .send(mockLoginUser);

    const data = await request(app.getHttpServer())
      .put('/me/update')
      .send(mockUser)
      .expect('success');
  });

  afterAll(async () => {
    await app.close();
  });
});

user.controller.ts

  @UseGuards(jwtAuthGuard)
  @Put('me/update')
  async updateUser(@Req() request, @Body() updateUser: UpdateUserDto) {
    const data = await this.userService.updateUser(request.user.id, updateUser);
    return data;
  }

jwt.strategy.ts

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor() {
    super({
      jwtFromRequest: (req) => {
        var token = null;
        if (req && req.cookies) {
          token = req.cookies['jwt'];
        }
        return token;
      },
      ignoreExpiration: false,
      secretOrKey: process.env.ACCESS_SECRET,
    });
  }

  async validate(payload: any) {
    return {
      id: payload.id,
      email: payload.email,
    };
  }
}

I’m trying to get e2e testing to work for this user update function. When user logs in their id and email are saved into JWT token and stored in HttpOnly Cookie. My problem is how to get this token so that it passes through JWT guard, gets id from JWT token and updates correct user. Because currently i'm obviously getting Unauthorized message.

user.2e2-spec.ts

const mockUser: UpdateUserDto = {
  email: '[email protected]',
  first_name: 'first_name1',
  last_name: 'last_name1',
  password: 'password1',
};

const mockLoginUser: LoginUserDto = {
  email: '[email protected]',
  password: 'password',
};

describe('Auth controller (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('should update user info', async () => {
    const loginRes = await request(app.getHttpServer())
      .post('/login')
      .send(mockLoginUser);

    const data = await request(app.getHttpServer())
      .put('/me/update')
      .send(mockUser)
      .expect('success');
  });

  afterAll(async () => {
    await app.close();
  });
});

user.controller.ts

  @UseGuards(jwtAuthGuard)
  @Put('me/update')
  async updateUser(@Req() request, @Body() updateUser: UpdateUserDto) {
    const data = await this.userService.updateUser(request.user.id, updateUser);
    return data;
  }

jwt.strategy.ts

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor() {
    super({
      jwtFromRequest: (req) => {
        var token = null;
        if (req && req.cookies) {
          token = req.cookies['jwt'];
        }
        return token;
      },
      ignoreExpiration: false,
      secretOrKey: process.env.ACCESS_SECRET,
    });
  }

  async validate(payload: any) {
    return {
      id: payload.id,
      email: payload.email,
    };
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟若柳尘 2025-02-01 00:30:37

您必须在呼叫之间自己处理这一点:

  it('should update user info', async () => {
    const loginRes = await request(app.getHttpServer())
      .post('/login')
      .send(mockLoginUser);

    const cookies = loginRes.header('set-cookie');

    const data = await request(app.getHttpServer())
      .put('/me/update')
      .set('Cookie', cookies) // Set the cookies from login response on new req
      .send(mockUser)
      .expect('success');
  });

如果使用typeScript,superagent supertest使用的,将为您提供set set set函数的提示,它接受只能是cookie的字段参数

You have to handle that yourself between calls:

  it('should update user info', async () => {
    const loginRes = await request(app.getHttpServer())
      .post('/login')
      .send(mockLoginUser);

    const cookies = loginRes.header('set-cookie');

    const data = await request(app.getHttpServer())
      .put('/me/update')
      .set('Cookie', cookies) // Set the cookies from login response on new req
      .send(mockUser)
      .expect('success');
  });

If using typescript, superagent which is used by supertest will give you a hint of the set function, it accepts a field parameter which only can be Cookie

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文