// utils/auth.js
import { parse, serialize } from 'cookie';
const MAX_AGE = 60 * 60 * 24 * 7; // 1 week in seconds
// Function to set secure cookies
export function setAuthCookies(res, accessToken, refreshToken) {
const accessTokenCookie = serialize('access_token', accessToken, {
maxAge: MAX_AGE,
httpOnly: true,
secure: process.env.NODE_ENV === 'production', // Set "secure" to true in production
path: '/',
});
const refreshTokenCookie = serialize('refresh_token', refreshToken, {
maxAge: MAX_AGE,
httpOnly: true,
secure: process.env.NODE_ENV === 'production', // Set "secure" to true in production
path: '/',
});
res.setHeader('Set-Cookie', [accessTokenCookie, refreshTokenCookie]);
}
// Function to get JWT tokens from cookies
export function getAuthCookies(req) {
return parse(req.headers.cookie || '');
}
import { setAuthCookies } from '../utils/auth';
// Assuming you have accessToken and refreshToken from the server response
setAuthCookies(res, accessToken, refreshToken);
型 要在后续请求中访问令牌,您可以在API函数中使用getAuthCookies:
import { getAuthCookies } from '../../utils/auth';
export default async function handler(req, res) {
const { access_token, refresh_token } = getAuthCookies(req);
// Now you can use access_token and refresh_token for authentication
}
2条答案
按热度按时间vcirk6k61#
Next.js和Django JWT认证|第1部分-后端API
Next.js和Django JWT认证|第2部分-前端
2exbekwf2#
您可以将jwt令牌存储在安全cookie或本地存储中
与本地存储相比,安全cookie更安全
字符串
成功登录或注册后,您可以使用setAuthCookies将令牌存储在响应中://登录或注册成功后
型
要在后续请求中访问令牌,您可以在API函数中使用getAuthCookies:
型