如何使用 PassportJS 保护 API 端点?

编程入门 行业动态 更新时间:2024-10-26 00:31:37
本文介绍了如何使用 PassportJS 保护 API 端点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我的应用程序使用 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 00:05:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1012529.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   PassportJS   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!