Saturday, 22 April 2017

authentication of user using nodejs+express+passport local strategy and new angular

I have followed every blog which describe how to use local strategy with passport running on express. the users data sits on mysql, and i have created the server code

let express = require('express')
let bodyParser = require('body-parser');
let path = require('path');
let app = express()
let cors = require('cors');
let passport = require('passport');
let flash = require('connect-flash');

let morgan = require('morgan');
let cookieParser = require('cookie-parser');
let session = require('express-session');


app.use(morgan('dev')); // log every request to the console

app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: false }))

app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-
   With, Content-Type, Accept");
   next();
});



app.use(cors());
app.use('/', express.static(path.join(__dirname, 'public')));

app.use(session({
   secret: 'secretme',
   resave: true,
   saveUninitialized: true
})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in 
      session

require('./config/passport')(passport); // pass passport for 
       configuration

function isAuthenticated(req, res, next) {

    //if (req.user && req.user.authenticated)
    //    return next();
    if (req.isAuthenticated())
        return next();

    res.status(401).send()
}

app.get('/api/about', isAuthenticated, (req, res) => {
    res.json({
        version: '1.1'
    })
})

the login pass ok, this is the function:

 app.post('/api/login', passport.authenticate('local-login', {
failureRedirect: '/bad-login',
failureFlash: true // allow flash messages
}), (req, res) => {
     res.status(200).send();
})

regarding the client side, I am using Angular v4 , the login call pass ok

login(email: string, password: string) {
  var headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
  let options = new RequestOptions({
    headers: headers
  })
  let data = new URLSearchParams();
  data.append('email', email);
  data.append('password', password);
  let body = data.toString()
  return  this._http.post(`http://X.X.X.X/api/login`, body, options)
  .toPromise()
  .then(response => response.status)
}

how ever when I call the about api , I am getting 401. What did i missed?

about(): Promise<About> {
    return this._http.get(`http://X.X.X.X/api/about`, { withCredentials: true })
    .toPromise()
    .then(response => response.json() as About)
}



via li-raz

No comments:

Post a Comment