使用Node.js创建OAuth2服务器

15

我正在学习REST API安全性,似乎许多人都在使用OAuth2和OpenId协议来管理身份验证。

我试图使用以下两个OAuth2服务器:

对于第一个解决方案,运行示例正常工作,但我需要使其无状态(在示例中,作者使用会话......)

您能帮助我创建可能的最简单的OAuth2服务器,或默认地向我解释这些库的整个功能吗?

提前感谢

1个回答

33

我使用了"oauth2-server": "^3.0.0-b2"进行实现。

var express = require('express');
var oauthServer = require('oauth2-server');
var Request = oauthServer.Request;
var Response = oauthServer.Response;
var authenticate = require('./components/oauth/authenticate')

var app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

// https://github.com/manjeshpv/node-oauth2-server-implementation/blob/master/components/oauth/models.js
var oauth = new oauthServer({
  model: require('./models.js')
});

app.all('/oauth/token', function(req,res,next){
    var request = new Request(req);
    var response = new Response(res);

    oauth
      .token(request,response)
      .then(function(token) {
        // Todo: remove unnecessary values in response
        return res.json(token)
      }).catch(function(err){
        return res.status( 500).json(err)
      })
  });

  app.post('/authorise', function(req, res){
    var request = new Request(req);
    var response = new Response(res);

    return oauth.authorize(request, response).then(function(success) {
        res.json(success)
    }).catch(function(err){
      res.status(err.code || 500).json(err)
    })
  });

app.get('/secure', authenticate(), function(req,res){
  res.json({message: 'Secure data'})
});

app.get('/me', authenticate(), function(req,res){
  res.json({
    me: req.user,
    messsage: 'Authorization success, Without Scopes, Try accessing /profile with `profile` scope',
    description: 'Try postman https://www.getpostman.com/collections/37afd82600127fbeef28',
    more: 'pass `profile` scope while Authorize'
  })
});

app.get('/profile', authenticate({scope:'profile'}), function(req,res){
  res.json({
    profile: req.user
  })
});

app.listen(3000);

使用Postman进行模拟: https://www.getpostman.com/collections/37afd82600127fbeef28

兼容MySQL/PostgreSQL/MSSQL: https://github.com/manjeshpv/node-oauth2-server-implementation/blob/master/components/oauth/models.js

MySQL数据定义语言(DDL): https://github.com/manjeshpv/node-oauth2-server-implementation/blob/master/sql/oauth_demo.sql

Mongo Dump文件: https://github.com/manjeshpv/node-oauth2-server-implementation/tree/master/mongo-dump

请注意,它们存在一个问题,需要用以下代码替换validateScope函数:

function validateScope(user, client) {
  return user.scope === client.scope
}

你可以分享一下 Git 的示例项目吗?我是 Node.js 和 Express 的新手。但是我需要实现 OAuth2 服务器。感到有些困惑。 - coder
1
如何配置才能与 https://developers.google.com/actions/identity/oauth2-code-flow 集成? - endamaco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接