2014-09-23 2 views
9

Я действительно изучаю защиту REST Apis, и, похоже, многие люди используют протоколи OAuth2 и OpenId для управления аутентификацией.Создание сервера OAuth2 с nodejs

Я пытался реализовать два сервера 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 и выражаю. Но мне нужно реализовать сервер oauth2. Путаница – coder

+2

https://github.com/manjeshpv/node-oauth2-server-implementation/ –

+1

Как это настроить, чтобы быть интегрированным с https://developers.google.com/actions/identity/oauth2-code -течь ? – endamaco

Смежные вопросы