我正在尝试使用accessToken和refreshToken实现JWT授权。accessstoken和refresh令牌都需要在HTTP 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 ?
这是我的主要。文件:-
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
评论中的对话:
在客户端,Axios需要将withCredentials
设置为true
以将cookie发送回服务器。服务器按预期发送和设置cookie
我遇到了几乎和你一样的问题。Axios无法保存cookie。设置SameSite所需的Chrome: 'none', secure: true。你仍然没有工作。它确实使用fetch方法保存了cookie,但仅在运行Chromium的浏览器中…所以mozilla没有收到它。我的公理是:
const response = await axios.post(url+'/login', loginState, {withCredentials: true});
后端:Main.ts:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('v1/api');
app.use(cookieParser());
app.useGlobalPipes(new ValidationPipe());
app.enableCors({
credentials: true,
origin: process.env.FRONTEND_URL,
})
await app.listen(3000);
}
我的AuthService登录函数(记住Res中的passthrought: true)
@Post('login')
async login(
@Body()body: LoginUserDTO,
@Res({passthrough: true}) response: Response
): Promise<any> {
const user = await this.userService.getOne({where: {"user_email": body.email}});
if(!user) {
throw new NotFoundException('User not found')
}
if(!await bcrypt.compare(body.password, user.user_password)) {
throw new BadRequestException('Password incorrect');
}
const frontendDomain = this.configService.get<string>('FRONTEND_DOMAIN');
const jwtToken = await this.jwtService.signAsync({id: user.user_id});
response.cookie('jwt', jwtToken, {httpOnly: true, domain: frontendDomain,});
return {'jwt': jwtToken}
}
奇怪的是,解决我的问题的方法是将域名添加到response.cookie.
我的开发环境变量用于CORS和cookie域:
FRONTEND_URL = http://localhost:3333
FRONTEND_DOMAIN = localhost
希望我的代码能帮到你