[英]How can i get next-auth session in nextjs 12 middlware
I was experimenting with the new nextjs features and while using next-auth inside the pages/_middleware.ts this doesn't seem to work我正在尝试新的 nextjs 功能,在 pages/_middleware.ts 中使用 next-auth 时,这似乎不起作用
import { getSession } from 'next-auth/client';
import type { NextFetchEvent, NextRequest } from 'next/server'
import {NextResponse} from 'next/server'
async function middleware(req: NextRequest, ev: NextFetchEvent) {
let session = await getSession({ req });
return new Response('Auth required', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Secure Area"',
},
})
}
export {middleware}
this works in api routes but the "req" object is NextApiRequest unlike here.这适用于 api 路由,但“req”对象是 NextApiRequest 与此处不同。 so how can i get the user object inside the middleware so i can do a role/authentication check.那么如何在中间件中获取用户对象,以便进行角色/身份验证检查。
What worked for me was to use the helper function getToken()
and decrypt the session information from the token which will be sent along with the request, ie req parameter对我有用的是使用辅助函数getToken()
并从将与请求一起发送的令牌中解密会话信息,即req参数
Here is a sample of my _middleware.ts这是我的 _middleware.ts 示例
export async function middleware(
req: NextApiRequest,
ev: NextFetchEvent
) {
const token = await getToken({
req,
secret: process.env.SECRET,
});
console.log("from middleware ", token);
return NextResponse.next();
}
Note process.env.SECRET refers to the secret you used in your [...nextauth].ts
configuration for jwt注意process.env.SECRET是指您在jwt的[...nextauth].ts
配置中使用的秘密
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.