Passport authentication middle ware is used here , invoked api http://localhost:3030/home/ but its throwing
error
angular.js:12587 POST http://localhost:3030/home/ 401 (Unauthorized).
angular.js:14525 Possibly unhandled rejection: {"data":"Unauthorized","status":401,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:3030/home/","headers":{"Accept":"application/json, text/plain, /"}},"statusText":"Unauthorized"}
route.js
module.exports = function(app , passport){
app.use('/login',userCtrl);
app.use('/register',registerCtrl);
app.use('/home', passport.authenticate('jwt', { session: false }) , homerCtrl);
};
passposrt.js
var JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require("passport-jwt").ExtractJwt;
var config = require('./appConfig.js');
module.exports = function(passport){
var jwtOptions = {}
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeader();
jwtOptions.secretOrKey = config.secret;
var strategy = new JwtStrategy(jwtOptions, function(jwt_payload, next) {
var user = users[_.findIndex(users, {id: jwt_payload.id})];
if (user) {
next(null, user);
} else {
next(null, false);
}
});
passport.use(strategy); }`
HomeCtrl
var mongoose = require("mongoose");
var User = mongoose.model("user");
var express = require("express");
var jwt = require('jsonwebtoken');
var config = require('./../config/appConfig.js');
//Type 1 using router
var router = express.Router();
router.post('/' , function(req, res, next){
var formData = req.body;
getUserData(formData , function(user){
res.json({ "responseMessage" : "Home Api Sucess" });
});
});
function getUserData(formData , cb){
User.findOne({username : formData.username}).then(function(user){
cb(user);
}).catch(function(err){
cb(err);
});
}
module.exports = router;
via Haris KK
No comments:
Post a Comment