gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:35:11 25 4
gpt4 key购买 nike

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

最佳答案

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)
然后在您的组件代码上:
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>
</>}
</>
}
如果您共享更多您拥有的身份验证路线,这将很容易让您入门,我可以提供更多建议。

关于javascript - Next Js 结合外部 REST API 身份验证和授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65451349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com