Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict'
- import * as jwt from 'jsonwebtoken'
- import * as HapiAuthJwt from 'hapi-auth-jwt'
- import * as Bcrypt from 'bcrypt'
- const privateKey = 'YourApplicationsPrivateKey'
- const accounts = {
- john: { // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImpvaG4iLCJpYXQiOjE0NTI3MDczMTJ9.ql2-znt55Ct6ApgJQKrRea2dfrLO85yL_poYPHNIZe8
- id: 123,
- username: 'john',
- password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm', // 'secret'
- fullName: 'John Q Public'
- }
- }
- const token = jwt.sign({ username: 'john' }, privateKey, { algorithm: 'HS256'})
- console.log(`TOKEN: ${token}`)
- const validateJwt = (request, decodedToken, callback) => {
- console.log(decodedToken) // should be {accountId : 123}.
- if (decodedToken)
- console.log(decodedToken.username.toString())
- const account = accounts[decodedToken.username]
- if (!account)
- return callback(null, false)
- return callback( null, true, account )
- }
- const validateBasic = function (request, username, password, callback) {
- const user = accounts[username]
- if (!user)
- return callback(null, false);
- Bcrypt.compare(password, user.password, (err, isValid) => {
- callback(err, isValid, {
- id: user.id,
- name: user.fullName,
- username: username,
- token: jwt.sign({ username: username }, privateKey, { algorithm: 'HS256'})
- });
- });
- };
- /**
- * To test:
- * curl -v -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhY2NvdW50SWQiOjEyMywiaWF0IjoxMzkyNTg2NzgwfQ.nZT1lsYoJvudjEYodUdgPR-32NNHk7uSnIHeIHY5se0" http://localhost:8000/tokenRequired echo
- */
- exports.register = ( server, options, next ) => {
- server.register(require('hapi-auth-basic'), (err) => {
- server.auth.strategy('simple', 'basic', { validateFunc: validateBasic })
- })
- server.register(HapiAuthJwt, () => {
- server.auth.strategy('token', 'jwt', {
- key: privateKey,
- validateFunc: validateJwt,
- verifyOptions: { algorithms: [ 'HS256' ] }
- })
- })
- next()
- }
- exports.register.attributes = {
- pkg: {
- name: "jwt_auth",
- version: "0.1.0"
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement