Pau*_*llo 6 javascript authentication reactjs next.js next-auth
我有一个现有的 Django 项目,我正在尝试将其从模板移动到 NextJs 前端。我遇到了 Next-Auth-js,它在 Next Auth 中似乎不错。
然而,该文档似乎更关注与 JS 相关的后端身份验证。按照此示例,我已将 NEXTAUTH_URL 环境变量发送到我的 DRF 端点 localhost:8002。当前端运行在 localhost:3000 上时。虽然我的 _app.js 看起来像这样:
<Provider options={{site: process.env.NEXTAUTH_URL,}} session={pageProps.session} >
<Component {...pageProps} />
</Provider>
Run Code Online (Sandbox Code Playgroud)
使用Nav.js进行测试,我更改了登录/退出 href 以指向我的 Django 端点,但似乎 next-auth-js 忽略了这一点,并将会话提取放置到我的前端http://localhost:3000/api/auth/session
而不是http://localhost:8002/api/auth/session
.
对于如何使用 Django Rest Framework (DRF) 正确/安全地实现此身份验证的任何帮助,我将不胜感激
我认为这就是它应该工作的方式,你的 nextjs 网站将是你的 django API 的一种代理/中间件client -> nextjs -> DRF
,你应该让它处理会话,并且对于你需要在 API 中执行任何身份验证步骤的任何操作,将代码来命中回调或事件配置中的这些端点,我认为本教程更适合您的用例
从文档
页面/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 */ },
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6467 次 |
最近记录: |