如何在 NextJS API Backend 中使用授权?

问题描述 投票:0回答:1

我有使用 prisma 作为 ORM 的 nextjs 应用程序。我有这个页面:/somecats 连接到 nextjs 后端(/pages/api/categories)。当我执行 http://localhost:3000/api/requests 时,它不需要授权。我希望这个端点应该被授权。我怎样才能在 NextJS 中做到这一点,尤其是使用 next-connect?

我已经尝试过这个教程但是它没有用,仍然没有授权。

这是 /pages/api/categories/index.js 现在还没有授权:

import { getCategories, postCategory } from '../../../database/controller';
import nc from 'next-connect';
import { verify } from 'jsonwebtoken';

const handler = nc({
    onError: (err, req, res, next) => {
        console.error(err.stack);
        return res.status(500).end(err);
    },
    onNoMatch: (req, res, next) => {
        return res.status(404).end("Page is not found");
    },
}).use((req, res, next) => {
    req.userId = null;
    req.username = null;

    const { authorization } = req.headers;

    if (!authorization) {
        next();
    } else {
        verify(authorization, 'khidir-secret', (error, decoded) => {
            if (!error && decoded) {
                req.userId = decoded.userId;
                req.username = decoded.name;
            }

            next();
        });
    }
})

    .get(async (req, res) => getCategories(req, res))
    .post(async (req, res) => postCategory(req, res))

export default handler;

该代码有效,但没有授权。我该怎么办?

next.js authorization next-connect
1个回答
0
投票

您提供的代码已经在 NextJS API 后端使用授权中间件。授权中间件从请求中提取授权标头并使用 verify 方法对其进行验证。如果授权标头存在且验证成功,它会在请求对象中设置 userId 和 username 属性。

要使用授权,您需要在向此 API 发出请求时传递带有有效令牌的授权标头。例如,您可以使用 fetch API 发出带有授权标头的请求,如下所示:

const token = 'valid_token_here';
fetch('/api/categories', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({ name: 'Category Name' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

在上面的示例中,Authorization 标头设置了一个 Bearer 令牌,该令牌与有效令牌值连接在一起。此令牌将由 API 后端的中间件进行验证,如果有效,则将在 req 对象中设置 userId 和 username 属性。

注意:您提供的代码中没有定义中间件中使用的verify方法。您需要从像 jsonwebtoken 这样的库中导入它才能使用它。

© www.soinside.com 2019 - 2024. All rights reserved.