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

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

问题描述

我的应用使用Express和AngularJS。我正在使用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 项目我在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 中调用中间件函数 ensureAuthenticated ensureAdmin 在routes.js 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

>

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);

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