Looking to implement the JWT strategy into my Hapi.js backend for heightened security and improved authentication processes. Here's a snippet of my server code:
const Hapi = require('@hapi/hapi');
const Joi = require('joi');
const Inert = require('inert');
const Vision = require('vision');
const HapiSwaggered = require('hapi-swaggered');
const HapiSwaggeredUI = require('hapi-swaggered-ui');
const knexConfig = require('./knexfile.js')
const knex = require('knex')(knexConfig.development)
const Jwt = require('@hapi/jwt')
const init = async () => {
// Server setup and configurations
const server = Hapi.Server({
port: 4545,
host: 'localhost',
"routes": {
"cors": {
"origin": ["*"],
"headers": ["Accept", "Content-Type"],
"additionalHeaders": ["X-Requested-With"]
}
}
});
// CORS handling
server.ext('onPreResponse', (request, h) => {
const response = request.response;
if (response.isBoom) {
response.output.headers['Access-Control-Allow-Origin'] = 'https://hapi.dev';
response.output.headers['Access-Control-Allow-Header'] = '*';
} else {
response.headers['Access-Control-Allow-Origin'] = 'https://hapi.dev';
response.headers['Access-Control-Allow-Headers'] = '*';
}
return h.continue;
});
// JWT plugin registration
await server.register(Jwt)
// JWT authentication strategy
server.auth.strategy('my_jwt_strategy', 'jwt', {
keys: 'some_shared_secret',
verify: {
aud: 'urn:audience:test',
iss: 'urn:issuer:test',
sub: false,
nbf: true,
exp: true,
maxAgeSec: 14400, // 4 hours
timeSkewSec: 15
},
validate: (artifacts, request, h) => {
console.log('Validation: Start');
console.log('Decoded JWT:', artifacts.decoded);
// Custom validation logic
console.log('Validation: End');
return { isValid: true }; // Replace with actual validation result
}
});
server.auth.default('my_jwt_strategy');
// Routes for login, register, and home
server.route({
method: 'POST',
path: '/login',
handler: async (request, h) => {
// Authentication logic
const { username, password } = request.payload;
if (username === 'exampleUser' && password === 'examplePassword') {
const token = Jwt.token.generate({ user: username }, 'some_shared_secret');
return { token };
} else {
return h.response({ message: 'Invalid credentials' }).code(401);
}
},
options: {
auth: false
}
});
// Other route definitions...
await server.start();
console.log('Server started on port 4545!');
};
// Error handling
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
Started with a register request to obtain a JWT token:
await fetch('http://localhost:4545/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({username: 'balbalsbd', password: 'asdasdada'})
})
.then(response => {
if (response.ok) {
return response.json();
} else {
return Promise.reject({ status: response.status, message: response.statusText });
}
})
.then(data => {
console.log('Registration successful:', data);
})
.catch(error => {
console.error('Registration failed:', error);
});
Used the obtained token to send a request to the / route for JWT functionality testing, but encountered a 401 error:
await fetch('http://localhost:4545/', {
method: 'GET',
headers: {
'Authorization': `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYXNkc2QiLCJpYXQiOjE3MTExMTM5OTR9.5xND-Cp6G8w89R9Qpc6lWpVzf9CQ9lNM3mCk9EURYhw`
}
})
.then(response => {
if (response.ok) {
return response.json();
} else {
return Promise.reject({ status: response.status, message: response.statusText });
}
})
.then(data => {
console.log('Response:', data);
})
.catch(error => {
console.error('Error:', error);
});