angularjs - Angular JS + Node JS + Passport + Spring OAuth2 Authentication/Authorization -
i new passportjs , angularjs , have doubt how proceed authorization.
i have spring rest api secured oauth2, have send user credentials this:
[http://localhost:8080/myapp/oauth/token] grant_type=password&username=email&password=password&client_id=09e749d8309f4044&client_secret=189309492722aa5a&scope=read
in client application use passport , want authorize/authenticate users, how can create stratagy ?
i send here server config , security lib.
server.js
var fs = require('fs'); var http = require('http'); var https = require('https'); var privatekey = fs.readfilesync(__dirname + '/cert/privatekey.pem').tostring(); var certificate = fs.readfilesync(__dirname + '/cert/certificate.pem').tostring(); var credentials = {key: privatekey, cert: certificate}; var express = require('express'); var config = require('./config.js'); var passport = require('passport'); var security = require('./lib/security'); var xsrf = require('./lib/xsrf'); var protectjson = require('./lib/protectjson'); require('express-namespace'); var app = express(); var secureserver = https.createserver(credentials, app); var server = http.createserver(app); // serve favicon app.use(express.favicon(config.server.distfolder + '/favicon.ico')); // first looks static file: index.html, css, images, etc. app.use(config.server.staticurl, express.compress()); app.use(config.server.staticurl, express['static'](config.server.distfolder)); app.use(config.server.staticurl, function(req, res, next) { res.send(404); // if here request static file invalid }); app.use(protectjson); app.use(express.logger()); // log requests console app.use(express.bodyparser()); // extract data body of request - needed localstrategy authenticate method app.use(express.cookieparser(config.server.cookiesecret)); // hash cookies secret app.use(express.cookiesession()); // store session in (secret) cookie app.use(passport.initialize()); // initialize passportjs app.use(passport.session()); // use passport's session authentication strategy - stores logged in user in session , run on request app.use(xsrf); // add xsrf checks request security.initialize(config.oauth.authorize_url, config.oauth.access_token, config.oauth.apikey, config.oauth.secretkey, config.oauth.scopereq); // add oauth strategy handling authentication app.use(function(req, res, next) { if ( req.user ) { console.log('current user:', req.user.firstname, req.user.lastname); } else { console.log('unauthenticated'); } next(); }); app.post('/login', security.login); app.post('/logout', security.logout); // retrieve current user app.get('/current-user', security.sendcurrentuser); // retrieve current user if authenticated app.get('/authenticated-user', function(req, res) { security.authenticationrequired(req, res, function() { security.sendcurrentuser(req, res); }); }); // retrieve current user if admin app.get('/admin-user', function(req, res) { security.adminrequired(req, res, function() { security.sendcurrentuser(req, res); }); }); // route deals enables html5mode forwarding missing files index.html app.all('/*', function(req, res) { // send index.html other files support html5mode res.sendfile('index.html', { root: config.server.distfolder }); }); // standard error handler - picks left on errors , returns nicely formatted server 500 error app.use(express.errorhandler({ dumpexceptions: true, showstack: true })); // start server on port specified in config server.listen(config.server.listenport, 'localhost', 511, function() { // // once server listening automatically open browser var open = require('open'); open('http://localhost:' + config.server.listenport + '/'); }); console.log('deengo business app server - listening on port: ' + config.server.listenport); secureserver.listen(config.server.secureport); console.log('deengo business app server - listening on secure port: ' + config.server.secureport);
lib/security.js
var express = require('express'); var passport = require('passport'); var app = express(); var bearerstrategy = require('passport-http-bearer').strategy var filteruser = function(user) { if ( user ) { return { user : { id: user._id.$oid, email: user.email, firstname: user.firstname, lastname: user.lastname, admin: user.admin } }; } else { return { user: null }; } }; var security = { initialize: function(_authorize_url, _access_token, _apikey, _secretkey, _scopereq) { passport.use('deengo-auth', new oauth2strategy({ authorizationurl: _authorize_url, tokenurl: _access_token, clientid: _apikey, clientsecret: _secretkey, callbackurl: 'http://localhost:3000/oauth/autorize/callback', scope: _scopereq, passreqtocallback: true, skipuserprofile: true }, function(req, accesstoken, refreshtoken, profile, done) { client['headers']['authorization'] = 'bearer ' + req.session.passport.accesstoken; user.findorcreate({ clientid: clientid }, function(err, user) { done(err, user); }); } )); }, authenticationrequired: function(req, res, next) { console.log('authrequired'); if (req.isauthenticated()) { next(); } else { res.json(401, filteruser(req.user)); } }, adminrequired: function(req, res, next) { console.log('adminrequired'); if (req.user && req.user.admin ) { next(); } else { res.json(401, filteruser(req.user)); } }, sendcurrentuser: function(req, res, next) { res.json(200, filteruser(req.user)); res.end(); }, login: function(req, res, next) { console.log(req.body.email); console.log(req.body.password); function authenticationfailed(err, user, info){ //if (err) { return next(err); } /*if (!user) { return res.json(filteruser(user)); } req.login(user, function(err) { if ( err ) { return next(err); } return res.json(filteruser(user)); });*/ } //passport.authenticate("deengo-auth", authenticationfailed)(req, res, next); return null; }, logout: function(req, res, next) { req.logout(); res.send(204); } }; module.exports = security;
lib/deengostrategy.js
var util = require('util'); var passport = require('passport'); var localstrategy = require('passport-local').strategy; var bearerstrategy = require('passport-http-bearer').strategy; var rest = require('request'); function deengoreststrategy(authorize_url, access_token, apikey, secretkey, scopereq) { this.authorize_url = authorize_url; this.access_token = access_token; this.apikey = apikey; this.secretkey = secretkey; this.scopereq = secretkey; this.baseurl = 'http://localhost:8080/deengo/api/'; // call super constructor - passing in our user verification function // use email field username localstrategy.call(this, { usernamefield: 'email' }, this.verifyuser.bind(this)); // serialize user string (id) storing in session passport.serializeuser(function(user, done) { done(null, user.id); }); // deserialize user string (id) user (via cll rest) passport.deserializeuser(this.get.bind(this)); // want strategy have nice name use passport, e.g. app.post('/login', passport.authenticate('deengo')); this.name = deengoreststrategy.name; } // deengoreststrategy inherits localstrategy util.inherits(deengoreststrategy, localstrategy); deengoreststrategy.name = "deengo"; // query users collection deengoreststrategy.prototype.query = function(query, done) { query.accesstoken = this.accesstoken; // add apikey passed in query var request = rest.get(this.baseurl, { qs: query, json: {} }, function(err, response, body) { done(err, body); }); }; // user id deengoreststrategy.prototype.get = function(id, done) { var query = { apikey: this.apikey }; var request = rest.get(this.baseurl + id, { qs: query, json: {} }, function(err, response, body) { done(err, body); }); }; // find user email deengoreststrategy.prototype.findbyemail = function(email, done) { this.query({ q: json.stringify({email: email}) }, function(err, result) { if ( result && result.length === 1 ) { return done(err, result[0]); } done(err, null); }); }; // check whether user passed in valid 1 deengoreststrategy.prototype.verifyuser = function(email, password, done) { this.findbyemail(email, function(err, user) { if (!err && user) { if (user.password !== password) { user = null; } } done(err, user); }); }; module.exports = deengoreststrategy;
i not know if have use passport-bearer or not , how use-it.
thanks in advance help.
regards,
eduardo.
i not know if have use passport-bearer or not , how use-it.
no. there other options, such as:
here example of how use passport:
// express using passport-local // code adaptation of examples/express3 https://github.com/jaredhanson/passport-local // configure express app.configure(function() { // ... app.use(express.session({ // domain should start dot, allows subdomain. domain: '.app.local', secret: 'keyboard cat' })); // enable cors. app.use(function(req, res, next) { res.header('access-control-allow-credentials', true); res.header('access-control-allow-origin', req.headers.origin); res.header('access-control-allow-methods', 'get,put,post,delete'); res.header('access-control-allow-headers', 'x-requested-with, x-http-method-override, content-type, accept'); next(); }); // ... }); app.get('/account', ensureauthenticated, function(req, res){ // return current user's info res.json(req.user); });
references
Comments
Post a Comment