我有一个退出的Django项目,我试图从模板转移到NextJs前端。我遇到了明年八月的事,这在明年八月似乎很不错。
然而,文档似乎更关注与JS相关的后端Auth。在这个示例之后,我将NEXTAUTH_URL环境变量发送到我的DRF localhost:8002。而前端运行在本地主机:3000。虽然我的_app.js看起来是这样的:
<Provider options={{site: process.env.NEXTAUTH_URL,}} session={pageProps.session} >
<Component {...pageProps} />
</Provider>使用Nav.js进行测试时,我将signin/out href更改为指向我的Django端点,但接下来的js似乎忽略了这一点,并将会话获取放在我的前端http://localhost:3000/api/auth/session而不是http://localhost:8002/api/auth/session上。
对于如何使用Django Rest框架(DRF)正确/安全地实现此身份验证,我将不胜感激。
发布于 2020-11-01 01:25:06
我认为这就是它的工作方式。,您的nextjs站点将是middleware 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 */ },
}发布于 2021-05-27 19:17:29
您可以在这里使用callbacks。https://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, account, profile, isNewUser) {
return token
}
}在signIn回调中,您可以从提供者登录获取accessToken和tokenId。在这里,调用您的DRF并将这些令牌传递给您的DRF,并且当您从DRF获得access_token和refresh_token时。将它们添加到用户实例中。然后在JWT回调中,从user获取access和refresh,并将它们添加到token中。
这是从某个博客上得到的

不过,您还需要处理刷新令牌。
https://stackoverflow.com/questions/64456054
复制相似问题