当给予外部访问令牌时,如何绕过NextAuth
这不是常见的用例,甚至不太好的做法,而是出于我的项目的目的,如果将访问令牌作为url中的参数传递(eghttp:// localhost:3000?accessToken = myaccesstoken),我需要在我的API调用中使用它,并使用下一个auth“禁用”身份验证。
身份验证过程只是一个后备,以防未传递访问。
我当前的实现是:
- 将访问权限存储在_app.tsx中的cookie中,在auth
之前 踢和重定向到登录页面:
我的_middleware.ts文件中的_app.tsx
...
// Retrieving the callbackURL query params.
const { callbackUrl } = router.query;
// Retrieving the accessToken from the callbackURL.
const params = new URL(callbackUrl as string, 'https://example').searchParams;
const accessToken = params.get('accessToken');
// Storing it in a cookie.
if (storeNumber) {
document.cookie = `storeNumber=${storeNumber}`;
}
...
- ,试图获取此cookie并授权 如果存在令牌,则登录。
_middleware.ts:
export default withAuth({
pages: {
signIn: '/auth/signin',
},
callbacks: {
authorized: ({ req, token }) => {
const accessToken = getCookie('accessToken'); // => null
return !!accessToken;
},
},
});
我什至不确定我可以从_middleware.ts文件访问cookie,或者如果是正确的方法。
任何帮助都将不胜感激。谢谢你们。
This is not a common use case and even less a good practice, but for the purposes of my project, if an access token is passed as a parameter in the url (e.g.http://localhost:3000?accessToken=myAccessToken), I need to use it in my API calls and "disable" authentication with next auth.
The authentication process is just a fallback in case an accessToken is not passed.
My current implementation is:
- storing the accessToken in a cookie in _app.tsx, before the auth
kicks and redirects to the login page :
_app.tsx
...
// Retrieving the callbackURL query params.
const { callbackUrl } = router.query;
// Retrieving the accessToken from the callbackURL.
const params = new URL(callbackUrl as string, 'https://example').searchParams;
const accessToken = params.get('accessToken');
// Storing it in a cookie.
if (storeNumber) {
document.cookie = `storeNumber=${storeNumber}`;
}
...
- in my _middleware.ts file, trying to get this cookie, and authorize
the login if the token is present.
_middleware.ts :
export default withAuth({
pages: {
signIn: '/auth/signin',
},
callbacks: {
authorized: ({ req, token }) => {
const accessToken = getCookie('accessToken'); // => null
return !!accessToken;
},
},
});
I'm not even sure I can access the cookie from the _middleware.ts file, or if it's the right way to do this.
Any help would really be appreciated. Thank you guys.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果有人想要解决方案(怀疑),我设法在这样的中间件中检索了cookie:
If anyone wants the solution (doubt it), I managed to retrieve the cookie in the middleware like this :