如何在django和nextjs 13之间进行身份验证?

cvxl0en2  于 2023-08-08  发布在  Go
关注(0)|答案(2)|浏览(110)

我可以在django和nextjs 13之间构建身份验证系统吗?
如果是的话,我该怎么做呢?我真的卡住了
我想使用基于JWT令牌的身份验证,但由于nextjs 13使用服务器组件,我不知道如何以及在哪里存储访问和刷新令牌。
谢谢...

vcirk6k6

vcirk6k61#

Next.js和Django JWT认证|第1部分-后端API
Next.js和Django JWT认证|第2部分-前端

2exbekwf

2exbekwf2#

您可以将jwt令牌存储在安全cookie或本地存储
与本地存储相比,安全cookie更安全

// 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 || '');
}

字符串
成功登录或注册后,您可以使用setAuthCookies将令牌存储在响应中://登录或注册成功后

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
}

相关问题