Currently, I am in the process of incorporating JWT authorization with both an accessToken and refreshToken. The requirement is to store these tokens in HTTP-only cookies.
Despite attempting this code snippet, I have encountered an issue where the cookies are not being set. My project utilizes the NestJS framework.
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;
}
}
}
The data retrieval using the res.send() method functions as expected, providing the necessary information in the response. However, the challenge lies in setting the cookie itself.
For reference, here is a snippet from my main.ts file:
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();
To access the cookie information, I am utilizing the following:
request.cookies