首页 > 解决方案 > 如何在 polka js 中保护路由

问题描述

我正在尝试使用 polka js 实现受保护的路由。我尝试使用中间件来实现它,但即使对于未受保护的路线,我也不断获得未经授权的许可。

const polka = require('polka');
const send = require('@polka/send-type');

const app = polka();

app.get('/un-protected', (req, res) => {
  return send(res, 200, {
    msg: 'Unprotected route',
  });
});

const auth = false;

app
  .use((req, res, next) => {
    if (auth) {
      next();
    } else {
      return send(res, 401, {
        errors: {
          msg: 'unauthorized',
        },
      });
    }
  })
  .get('/protected', (req, res) => {
    return send(res, 200, {
      msg: 'Protected route',
    });
  });

const PORT = process.env.PORT || 8080;

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

预期的行为是只有 '/protected' 路由应该显示未经授权的消息,但目前即使对于 '/un-protected' 路由,未经授权的消息也会不断弹出。

标签: node.jsroutingauthorization

解决方案


认证检查应该放在指定的路由和去保护路由时的动作之间。

app.get('/un-protected', (req, res) => {
  return send(res, 200, {
    msg: 'Unprotected route',
  });
});

const auth = false;

const checkAuth = (req, res, next) => {
  if (auth) {
    next();
  } else {
    return send(res, 401, {
      errors: {
        msg: 'unauthorized',
      },
    });
  }
}

app
  .get('/protected', checkAuth, (req, res) => {
    return send(res, 200, {
      msg: 'Protected route',
    });
  });

推荐阅读