Next Js 结合外部 REST API 身份验证和授权

Jus*_*res 6 javascript node.js express reactjs next.js

我已经有一个使用 Node Js 和 express 构建的应用程序,我也有一个使用 create-react-app 和 redux 的前端,但现在我想将其移至下一个 Js,但我陷入了困境,因为我不使用我的其余完整 API 进行身份验证和授权的正确方法,我想提一下,我的 API 已经使用 JWT 处理此问题(将其保存在 cookie 中)

4_5*_*5_4 8

在这种情况下, Next-Auth是一个首选。以下示例展示了如何开始使用密码身份验证。

创建一个名为/pages/api/auth/[...nextauth].js

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

const options = {
  providers: [
    Providers.Credentials({
    // The name to display on the sign in form (e.g. 'Sign in with...')
    name: 'Email and Password',
    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 eg from db or api
      const user = { id: 1, name: 'J Smith', email: 'jsmith@example.com' }

      if (user) {
        // 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
      }
    }
  }),
  ],
}

export default (req, res) => NextAuth(req, res, options)
Run Code Online (Sandbox Code Playgroud)

然后在你的组件代码上:

import React from 'react'
import {
  signIn, 
  signOut,
  useSession
} from 'next-auth/client'

export default function myComponent() {
  const [ session, loading ] = useSession()

  return <>
    {!session && <>
      Not signed in <br/>
      <button onClick={signIn}>Sign in</button>
    </>}
    {session && <>
      Signed in as {session.user.email} <br/>
      <button onClick={signOut}>Sign out</button>
    </>}
  </>
}
Run Code Online (Sandbox Code Playgroud)

这很容易让您开始,如果您分享更多的身份验证路线,我可以提供更多建议。

  • 您应该尝试回调中的会话方面 https://next-auth.js.org/configuration/options#callbacks。每次访问会话时都会调用它。另请参阅 https://next-auth.js.org/configuration/callbacks#session-callback (2认同)