Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

validateFunc function is not excuted or not called #204

Open
rssandy1991 opened this issue Oct 27, 2016 · 6 comments
Open

validateFunc function is not excuted or not called #204

rssandy1991 opened this issue Oct 27, 2016 · 6 comments

Comments

@rssandy1991
Copy link

Request is send to server then validateFunc fuction is not excuted and Unauthorized request display in chrome console.

@nelsonic
Copy link
Member

Hi @rssandy1991 can you please give us a bit more detail? If your code is open, please share a link to it, if not, can you paste a snippet of your server.js and 'validateFunc' here as a comment so we can help debug thanks!

@rssandy1991
Copy link
Author

***validateFunc function is not excuted and Request is send to server then validateFunc fuction is not excuted and Unauthorized request display in chrome console. ***

server.js code as below

'use strict';
const Hapi=require('hapi');
var jwt = require('jsonwebtoken');
const server=new Hapi.Server();
server.connection({port:3000,host: 'localhost', routes: {cors: true}});
var routes=require('./server/controllers/routes');

var people = {

username:'admin',
password:'admin'

};
var validate=function (decoded, request, callback) {
console.log("hi");
var token=request.headers.authorization;

console.log(token);
var decoded=jwt.verify(token,'admin');
if (people.password!=decoded.password && people.username!=decoded.username ) {
    return callback(null, false);
}
else {
    return callback(null, true);
}

};
server.register(require('hapi-auth-jwt2'), function (err) {

if (err) {
    console.log(err);
}

server.auth.strategy('jwt', 'jwt',
    {
        key: 'admin',         
        validateFunc: validate,           
        verifyOptions: {algorithms: ['HS256']} 
    });

server.auth.default('jwt');

server.route(routes);

});

server.start(function (err) {
if(err){
throw err;
}
});
console.log('server running at:'+server.info.uri);
module.exports = server;

Routes.js code show as below

var listings=require('../controllers/listings');
module.exports=[
{ path:"/listings/city/{city}",
method:"GET",
config:{auth:'jwt'},
handler:listings.search
},
{
path: "/listings/{id}",
config:{auth:'jwt'},
method: "GET",
handler:listings.show
},
{
path:"/listings/",
config:{auth:'jwt'},
method:"GET",
handler:listings.index
},
{
path:"/listings/login/user/",
config: { auth: false },
method:"POST",
handler:listings.login
}
];

@rssandy1991
Copy link
Author

front end Code

$http.get('http://localhost:3000/listings/', {
city:$scope.city
}).success(function(data, status, headers, config) {
console.log(data);
console.log( $scope.typedata);
});

@rug1
Copy link

rug1 commented Nov 3, 2016

I seem to be having a similar problem. I am trying to use Auth0 and hapi-auth-jwt2 but I am getting this error: {"statusCode":401,"error":"Unauthorized","message":"Missing authentication"}. It looks like my validate function is not running since no console logs are being printed.

This is my authentication.js which I have registered in my server setup file:

var env = require('env2')('.env');
var HapiAuthJWT =  require('hapi-auth-jwt2');

var validate = function (decoded, request, callback) {
  console.log("decoded------------->",decoded);
  if (!decoded) {
    return callback(null, false);
  } else {
    return callback(null, true);
  }
}

exports.register = function (server, options, next) {
  server.register(HapiAuthJWT, function (err) {

    server.auth.strategy('jwt', 'jwt', {
      key: Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
      validateFunc: validate,
      verifyOptions: {
        algorithms: [ 'HS256' ],
        audience: process.env.AUTH0_CLIENT_ID
      }
    });
    server.auth.default('jwt');
  });
  return next();
};

exports.register.attributes = {
  name: 'Authentication'
};

These are my routes which are also registered in my server setup file:

module.exports = [
  {
    method: 'GET',
    path: '/create-an-account',
    config: {
      auth: false
    },
    handler: function(request, reply) {
      var data = {
        siteWideVariables: siteWideVariables
      };
      return reply.view('create-an-account', data);
    }
  },
  {
    method: 'POST',
    path: '/create-an-account',
    config: {
      auth: false,
      validate: {
        payload: {
          fullName: Joi.string().required(),
          email: Joi.string().required().email(),
          mobileNumber: Joi.string().min(10).required(),
          token: Joi.string().required()
        },
        failAction: createAccountValidateHandler
      },
      handler: createAccountValidateHandler
    }
  },
  {
    method: 'GET',
    path: '/create-an-account/make-sure-this-is-right',
    handler: function(request, reply) {
      var data = {
        siteWideVariables: siteWideVariables,
        email: request.state.account.email
      };
      return reply.view('make-sure-this-is-right', data);
    }
  }
]

function createAccountValidateHandler(request, reply, source, error) {
  var data = validationHelper.checkForErrors(request, error);
  if (typeof data !== "undefined"){
    data.siteWideVariables = siteWideVariables;
    return reply.view('create-an-account', data).code(400);
  } else {
    return reply.redirect('/create-an-account/make-sure-this-is-right')
                .state('account', request.payload, {path: '/'})
                .header("Authorization", request.payload.token);
  }
}

When I get to the last endpoint which requires authentication nothing is getting into my validate function, I assume that is why I cannot access the endpoint. Any help with what I could be doing wrong would be greatly appreciated. Thanks!

@rug1 rug1 reopened this Nov 4, 2016
@rug1
Copy link

rug1 commented Nov 4, 2016

Reading through the closed issues it looks like #125 partly answers my question- Using https://jwt.io/ I can see that I don't have a valid JWT so the validate function will not run, however I'm not sure why my JWT is not valid

@bohrasankalp
Copy link

Any updates? I am getting the same issue. @rug1 As per your last comment, In case, if you have invalid JWT it should update like Invalid JWT instead of missing authentication.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants