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

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

问题描述

我的应用程序使用前preSS和AngularJS。我使用前preSS通过静态处理的角code的基本的网络seving。角code使用击中由前preSS托管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?

推荐答案

我已经上传了角防爆preSS的上我一直在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调用只有通过身份验证的用户访问,或只与管理员角色的用户。这是在服务器/ routes.js达到调用中间件功能 ensureAuthenticated ensureAdmin 这是定义在服务器/ 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

in 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天全站免登陆