如何在Next.js中保护API路由?

dfty9e19  于 2023-06-22  发布在  其他
关注(0)|答案(4)|浏览(115)

我正在使用Next.js API路由-https://nextjs.org/docs/api-routes/introduction,但我不知道如何保护它们不被公开。
现在这些路由在我的生产服务器中是公开的。
例如:当我在浏览器中转到mysite.com/api/cats时,它返回-

{ success: true, data: [...] }

请帮助,我如何隐藏这些API路由对公开?

9avjhtql

9avjhtql1#

如果您阻止浏览器请求URL,那么用户在地址栏中输入URL时将看不到数据**,并且**您的JavaScript在向同一URL发出 AJAX 请求时也不会看到数据。
您不能向浏览器用户隐藏数据,同时仍允许在同一浏览器中运行的应用程序访问数据。

i86rm4rw

i86rm4rw2#

使用getSession()#可以使用getSession()方法保护API路由。
Using getToken()#如果您使用的是JSON Web Token,您可以使用getToken()助手访问JWT的内容,而不必自己处理JWT解密/验证。此方法只能在服务器端使用。
请参阅此处:https://next-auth.js.org/tutorials/securing-pages-and-api-roads #:~:text=You%20can%20protect%20API%20routes%20using%20the%20getSession()%20method。

pn9klfpd

pn9klfpd3#

1.使用鉴权:

export default async function apiRouteName(req, res) {
  //way of getting the token totally depends on your preference
  let token = req.cookies.jwtToken || req.headers.jwtToken || req.query.jwtToken
  
  if(!token) {
    return res.status(401).json({message:"you are not allowed"});
  }
  
  let data = {}; //store your data in  this variable
  return res.status(200).json({data})
  
}

2.中间件:

import { NextResponse } from "next/server";

export function  middleware (req  ,  event ) {
   //way of getting the token totally depends on your preference
   let token = req.cookies.jwtToken || req.headers.jwtToken
   if (!token ) {
     return NextResponse.redirect('/login');
   }
   
    return NextResponse.next();
}
ac1kyiln

ac1kyiln4#

如果我理解你的问题,你想知道如何保护端点,以便你只能用令牌访问它们?
如果是这样,一个快速简单的方法是使用Next-Auth沿着getSession钩子。

import { getSession } from 'next-auth/react';
          
    export default async function handler(
            req: NextApiRequest,
            res: NextApiResponse<Data>
        ) {
            const session = await getSession({ req });

            if (!session)
                return res.status(401).send({
                    message: 'Unauthenticated user. Your IP has been logged',
                });
            //handle the request here
}

相关问题