如何使用 PassportJS 保护 API 端点? [英] How can I protect an API endpoint with PassportJS?

查看:32
本文介绍了如何使用 PassportJS 保护 API 端点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用 Express 和 AngularJS.我正在使用 express 通过静态处理角度代码的基本网络服务.angular 代码使用命中由 express 托管的 API 端点的服务.我只希望在用户通过身份验证后可以访问 API 端点.如何通过 PassportJS 完成此操作?

My app use Express and AngularJS. I'm using express to handle basic web seving of the angular code via static. The angular code uses services that hit API endpoints hosted by express. I only want the API endpoints to be accessible after a user has authenticated. How can I accomplish this via PassportJS?

推荐答案

我已经上传了一个 Angular-Express project 在 github 上,我一直在做.

I have uploaded an Angular-Express project on github that I have been working on.

它仍在进行中.我希望它有所帮助.

It is still work in progress. I hope it helps.

它使用 PassportJs 进行用户身份验证,是服务器端授权的基本示例.它演示了如何使 API 调用只能由经过身份验证的用户访问,或者只有具有管理员角色的用户才能访问.这是在 server/routes.js 调用中间件函数 ensureAuthenticatedensureAdmin 中实现的,这些函数定义在 server/authentication.js 中

It uses PassportJs for user authentication and is a basic example of server side authorization. It demonstrates how to make API calls accessible only to authenticated users, or only to users with admin role. This is achieved in server/routes.js calling the middleware functions ensureAuthenticated, and ensureAdmin which are defined in server/authentication.js

在routes.js

// anybody can access this 
app.get('/api/test/users', 
        api.testUsers);


// only logged-in users with ADMIN role can access this 
app.get('/api/users',          
        authentication.ensureAdmin,
        api.testUsers);

// only logged-in users can access this
app.get('/api/books', 
        authentication.ensureAuthenticated, 
        api.books);

在 authentication.js 中

in authentication.js

ensureAuthenticated: function(req, res, next) {
    if (req.isAuthenticated()) {
       return next();
    } else {
       return res.send(401);
    }
},

ensureAdmin: function(req, res, next) {
  // ensure authenticated user exists with admin role, 
  // otherwise send 401 response status
  if (req.user && req.user.role == 'ADMIN') {
      return next();
  } else {
      return res.send(401);
  }
},

这篇关于如何使用 PassportJS 保护 API 端点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆