如何在 next-auth 中保护多个 Next.js API 路由
How can I protect multiple Next.js API routes in next-auth
我在 Next.js 中构建了一个简单的 API 并使用 next-auth 进行身份验证。
到目前为止,我必须在每个 API 路线中使用类似的东西:
const session = await getSession({ req });
if (session) {
... do something ...
} else {
... send back a 401 status
}
这似乎违背了DRY原则。有没有一种巧妙的方法可以在一个地方对多个路由应用保护,例如Laravel个路由组?
创建一个获取会话的中间件,否则returns 401.
请参阅 api middleware 上的 NextJS 文档。
您还可以在 github 存储库中查看 their example。
做一个中间件!
如果您不使用 TS,请忽略输入
import { NextApiRequest, NextApiResponse } from 'next/types'
import { getSession } from 'next-auth/client'
export const protect = async (
req: NextApiRequest,
res: NextApiResponse,
next: any
) => {
const session = await getSession({ req })
if (session) {
console.log(session)
next()
} else {
res.status(401)
throw new Error('Not authorized')
}
}
我在 Next.js 中构建了一个简单的 API 并使用 next-auth 进行身份验证。
到目前为止,我必须在每个 API 路线中使用类似的东西:
const session = await getSession({ req });
if (session) {
... do something ...
} else {
... send back a 401 status
}
这似乎违背了DRY原则。有没有一种巧妙的方法可以在一个地方对多个路由应用保护,例如Laravel个路由组?
创建一个获取会话的中间件,否则returns 401.
请参阅 api middleware 上的 NextJS 文档。
您还可以在 github 存储库中查看 their example。
做一个中间件!
如果您不使用 TS,请忽略输入
import { NextApiRequest, NextApiResponse } from 'next/types'
import { getSession } from 'next-auth/client'
export const protect = async (
req: NextApiRequest,
res: NextApiResponse,
next: any
) => {
const session = await getSession({ req })
if (session) {
console.log(session)
next()
} else {
res.status(401)
throw new Error('Not authorized')
}
}