2014-09-23 121 views
9

實際上,我正在研究REST Apis安全性,而且似乎很多人都在使用OAuth2和OpenId協議來管理身份驗證。使用nodejs創建OAuth2服務器

我曾嘗試使用,以實現兩個OAuth2用戶服務器:

對於第一種方案,運行這些示例工作正常,但我需要做一些無狀態的事情(在示例中爲auth或使用會話...)

你能幫我創建最簡單的oauth2服務器嗎?或者默認向我解釋這些庫的整個功能?

感謝提前

回答

13

我實現了使用"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); 

爲了模擬,用郵差:https://www.getpostman.com/collections/37afd82600127fbeef28

的MySQL/PostgreSQL的/ MSSQL Compatiable: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

蒙戈轉儲:需要被替換https://github.com/manjeshpv/node-oauth2-server-implementation/tree/master/mongo-dump

需要注意的是,他們有一個問題存在與validateScope功能:

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

你可以分享git的示例項目?我是nodejs和express的新手。但我需要實現oauth2服務器。感到困惑 – coder 2017-07-18 05:30:31

+2

https://github.com/manjeshpv/node-oauth2-server-implementation/ – 2017-07-21 11:50:27

+1

它將如何配置才能與https://developers.google.com/actions/identity/oauth2-code -流 ? – endamaco 2017-12-09 20:36:34