-
Notifications
You must be signed in to change notification settings - Fork 126
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
Add Basic usage example to README #13
Comments
UsageInstall from NPMnpm install hapi-auth-jwt2 --save ExampleThere is a an example in the /example directory of this repo But here are the basic usage to get started: var Hapi = require('hapi');
var JWT = require('jsonwebtoken'); // used to sign our content
var port = process.env.PORT || 8000; // allow port to be set
var secret = 'NeverShareYourSecret'; // Never Share This! even in private GitHub repos!
var people = { // our "users databse"
1: {
id: 1,
name: 'Anthony Valid User'
}
};
// use the token as the 'authorization' header in requests
var token = JWT.sign(people[1], secret); // synchronous
// bring your own validation function
var validate = function (decoded, callback) {
console.log(decoded);
// do your checks to see if the person is valid
if (!people[decoded.id]) {
return callback(null, false);
}
else {
return callback(null, true);
}
};
var server = new Hapi.Server();
server.connection({ port: port });
// include our module here ↓↓
server.register(require('hapi-auth-jwt2'), function (err) {
if(err){
console.log(err);
}
// see: http://hapijs.com/api#serverauthschemename-scheme
server.auth.strategy('jwt', 'jwt', true, { key: secret, validateFunc: validate });
server.route([
{
method: "GET", path: "/", config: { auth: false },
handler: function(request, reply) {
reply({text: 'Token not required'});
}
},
{
method: 'GET', path: '/restricted', config: { auth: 'jwt' },
handler: function(request, reply) {
reply({text: 'You used a Token!'}).header("Authorization", request.headers.authorization);
}
}
]);
});
server.start(); Run the server with: Now use curl to access the two routes: No Token Requiredcurl -v http://localhost:8000/ Token RequiredTry to access the /restricted content without supplying a Token curl -v http://localhost:8000/restricted Now access the url using the following format: A here's a valid token you can use: curl -v -H "Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwibmFtZSI6IkFudGhvbnkgVmFsaWQgVXNlciIsImlhdCI6MTQyNTQ3MzUzNX0.KA68l60mjiC8EXaC2odnjFwdIDxE__iDu5RwLdN1F2A" \
http://localhost:8000/restricted That's it. Write your own |
In addition to the /example it makes sense to have a simple example in the README
The text was updated successfully, but these errors were encountered: