I've been trying to authenticate my routes using a custom strategy that are based in the `passport-http' Basic strategy. This is the code for my strategy.
passport_auth.js
var BasicStrategy = require('passport-http').BasicStrategy;
module.exports.userBasic = (function(name){
var userAuthBasic = new BasicStrategy(
function(username, password, done) {
//My strategy
}
);
userAuthBasic.name = name;
return userAuthBasic;
})('userBasic');
Using IIFE I register the name of my strategy. Then in the file app.js
I invoke as following:
app.js
var express = require('express');
var bodyParser = require('body-parser');
var passport = require('passport');
var userRouter = require(__dirname+'/http/routers/user_router.js');
const cors = require('cors')();
var passportAuth = require(__dirname + '/http/passport_auth'); //My file with my strategy
//Adds to passport my strategy
passport.use(passportAuth.userBasic);
var app = express();
app.use(cors);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use('/user', passport.authenticate('userBasic', { session: false }), userRouter);
The userRouter
contains a several routes. When I try to POST to /user/anything always return 401 code status.
This Configuration is good? In other module the same code working fine, but in this case I've spent to much hours trying to solving this.
Solution The problem was that I wasn't sending the header for the authorization formed by: 'Basic' string + 'username : password' encoded in base 64.
In angular http response.
$http({
url: serverUrl,
method: 'POST',
headers: {'authorization': 'Basic ' + new Buffer(username + ':' + password).toString('base64');},
data: fields
})
credits to @Vadim answer in this post What are the differences between local Basic and Digest strategy in passportjs