简体   繁体   English

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

[英]How to protect API routes in Next.js?

I am using Next.js API routes - https://nextjs.org/docs/api-routes/introduction but I don't know how to protect them from public.我正在使用 Next.js API 路线 - https://nextjs.org/docs/api-routes/introduction但我不知道如何保护它们免受公众侵害。

Now those routes are public in my production server.现在这些路由在我的生产服务器中是公开的。

For example: when I go to mysite.com/api/cats in browser, it returns -例如:当我在浏览器中输入 go 到mysite.com/api/cats时,它返回 -

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

Please help, how do I hide those API routes from public?请帮助,我如何隐藏那些 API 公共路线?

If you prevent the browser from requesting the URL then the user won't see the data when they type the URL into the address bar and your JavaScript won't see it when it makes an Ajax request to the same URL. If you prevent the browser from requesting the URL then the user won't see the data when they type the URL into the address bar and your JavaScript won't see it when it makes an Ajax request to the same URL.

You can't hide the data from the user of the browser while still allowing your application running in the same browser to access it.您不能向浏览器用户隐藏数据,同时仍然允许在同一浏览器中运行的应用程序访问它。

Using getSession()# You can protect API routes using the getSession() method.使用 getSession()# 您可以使用 getSession() 方法保护 API 路由。

Using getToken()# If you are using JSON Web Tokens you can use the getToken() helper to access the contents of the JWT without having to handle JWT decryption / verification yourself. Using getToken()# If you are using JSON Web Tokens you can use the getToken() helper to access the contents of the JWT without having to handle JWT decryption / verification yourself. This method can only be used server side.此方法只能用于服务器端。

See here: https://next-auth.js.org/tutorials/securing-pages-and-api-routes#:~:text=You%20can%20protect%20API%20routes%20using%20the%20getSession()%20method .见这里: https://next-auth.js.org/tutorials/securing-pages-and-api-routes#:~:text=You%20can%20protect%20API%20routes%20using%20the%20getSession()% 20 方法

1.Use Authentication: 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.Middleware: 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(); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM