针对DRF的具有Next-Auth的NextJs身份验证

问题描述

我有一个退出的Django项目,我正在尝试将其从模板迁移到NextJs前端。我遇到了Next-Auth-js,在Next Auth中看起来不错。

但是,该文档似乎更关注与JS相关的后端身份验证。在此example之后,我已将NEXTAUTH_URL环境变量发送到我的DRF端点localhost:8002。而前端在localhost:3000上运行。虽然我的_app.js看起来像这样:

<Provider options={{site: process.env.NEXTAUTH_URL,}} session={pageProps.session}  >
  <Component {...pageProps} />
</Provider>

使用Nav.js进行测试,我将登录/注销href更改为指向我的Django端点,但是next-auth-js似乎忽略了这一点,并向我的前端http://localhost:3000/api/auth/session放置了会话而不是http://localhost:8002/api/auth/session

对于使用Django Rest Framework(DRF)如何正确/安全地实现身份验证的任何帮助,我将不胜感激

解决方法

我认为that is the way it should work,您的nextjs网站将是django API client -> nextjs -> DRF的一种代理/中间件,您应该让它处理会话以及您需要在API中执行的任何操作对于任何身份验证步骤,将代码放在callbacksevents配置中击中那些端点,我认为this tutorial对于您的用例更准确

来自docs

pages / api / auth / [... nextauth] .js

import Providers from `next-auth/providers`
...
providers: [
  Providers.Credentials({
    // The name to display on the sign in form (e.g. 'Sign in with...')
    name: 'Credentials',// The credentials is used to generate a suitable form on the sign in page.
    // You can specify whatever fields you are expecting to be submitted.
    // e.g. domain,username,password,2FA token,etc.
    credentials: {
      username: { label: "Username",type: "text",placeholder: "jsmith" },password: {  label: "Password",type: "password" }
    },authorize: async (credentials) => {
      // Add logic here to look up the user from the credentials supplied
      const user = { id: 1,name: 'J Smith',email: 'jsmith@example.com' }

      if (user) {
        // call your DRF sign in endpoint here
        // Any object returned will be saved in `user` property of the JWT
        return Promise.resolve(user)
      } else {
        // If you return null or false then the credentials will be rejected
        return Promise.resolve(null)
        // You can also Reject this callback with an Error or with a URL:
        // return Promise.reject(new Error('error message')) // Redirect to error page
        // return Promise.reject('/path/to/redirect')        // Redirect to a URL
      }
    }
  })
]

...

  events: {
    signOut: async (message) => { /* call your DRF sign out endpoint here */ },}
,

您可以在此处使用 callbackshttps://next-auth.js.org/configuration/callbacks

callbacks: {
  async signIn(user,account,profile) {
    return true
  },async redirect(url,baseUrl) {
    return baseUrl
  },async session(session,user) {
    return session
  },async jwt(token,user,profile,isNewUser) {
    return token
  }
}

signIn 回调中,您可以从提供者登录中获取 accessToken 和 tokenId。在这里,调用您的 DRF API 并将这些令牌传递给您的 DRF,当您从 DRF 取回 access_tokenrefresh_token 时。将它们添加到您的用户实例。然后在 JWT 回调中,从 access 获取 refreshuser 并将它们添加到 token

从某个博客得到这个

enter image description here

不过,您还需要处理刷新令牌。