【问题标题】:Protect api routes with middleware in nextJS?在 nextJS 中使用中间件保护 api 路由?
【发布时间】:2022-02-11 04:16:06
【问题描述】:

我是 next.js 的新手,我想知道是否可以通过中间件保护整个 API 路由。因此,例如,如果我想保护 /api/users 我可以创建 /api/users/_middleware.ts 并在中间件中处理身份验证,而不必担心实际 api 端点中的身份验证吗?如果是这样,我将如何去做?我现在使用的库是@auth0\nextjs-auth0,所以我猜它看起来像这样? (如果我写错了,请原谅我,我在stackoverflow编辑器中这样做)

export default authMiddleware(req,res)=>{
const {user,error,isLoading} = whateverTheNameOfTheAuth0HookIs()
if(user)
{
// Allow the request to the api route
}
else
{
// Deny the request with HTTP 401
}
}

我的总体思路是否正确?

【问题讨论】:

    标签: authentication next.js middleware auth0


    【解决方案1】:

    您可以为此使用中间件,类似于文档中的this example。

    对于pages 中的子目录,您可以创建一个_middleware.ts 文件。它将针对此目录中的所有页面运行。它看起来像这样:

    import { NextRequest, NextResponse } from 'next/server'
    
    export function middleware(req: NextRequest) {
      const basicAuth = req.headers.get('authorization')
    
      if (basicAuth) {
        // do whatever checks you need here
        const hasAccess = ...
    
        if (hasAccess) {
          // will render the specified page
          return NextResponse.next()
        }
      }
    
      // will not allow access
      return new Response('No access', {
        status: 401,
        headers: {
          'WWW-Authenticate': 'Basic realm="Secure Area"',
        },
      })
    }
    

    您可以在documentation找到更多信息。

    【讨论】:

    • 我知道它如何与基本身份验证一起使用,但您认为它是否也可以与我正在使用的第三方身份验证库一起使用?
    猜你喜欢
    • 1970-01-01
    • 2020-04-26
    • 2021-09-28
    • 2021-09-06
    • 2015-12-17
    • 2015-08-12
    • 2019-12-04
    • 1970-01-01
    • 2017-11-15
    相关资源
    最近更新 更多