Abubakr Shomirsaidov
Abubakr Shomirsaidov

Reputation: 25

Pending requests with authorization header (bearer token) - hapi.js + jwt

i have created and tested some api where the authorization strategy is jwt. when i test it in postman and other tools, the route /user is working perfect but if i do it from my own client (vue application) is starts pending infinitely... please, i would be pleased for any comment or advice, just say something i can do. here is my server code :

const Hapi = require('hapi');
const HapiAuth = require('hapi-auth-jwt2');
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 Register = require('./auth/register/index.js')
const Login = require('./auth/login/index.js')
const Profile = require('./profile/index.js')
const Lesson = require('./lessons/index.js')
const Progress = require('./progress/index.js')

const server = Hapi.Server({
    port: 4545,
    host: 'localhost',
    routes: {
        cors: {
            origin: ['*'],
            headers: ['Accept', 'Content-Type', 'Authorization'], // Include Authorization header
            additionalHeaders: ['X-Requested-With'],
        },
    },
});

const init = async () => {
    await server.register([
        HapiAuth,
        Inert,
        Vision,
        {
            plugin: HapiSwaggered,
            options: {
                info: {
                    title: 'Test API Documentation',
                    version: '1.0.0',
                },
            },
        },
        {
            plugin: HapiSwaggeredUI,
            options: {
                title: 'Swagger UI',
                path: '/docs',
            },
        },
    ]);

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

    await server.register([
        { plugin: Register },
        { plugin: Login },
        { plugin: Profile },
        { plugin: Lesson },
        { plugin: Progress }
    ]);

    server.route({
        method: 'OPTIONS',
        path: '/{any*}',
        handler: function (request, h) {
            return h.response().code(200);
        }
    });

    await server.start();
    console.log("Server has started on port 4545 successfully !");
};

const validate = (decoded, request, h) => {
    return { isValid: true };
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

here is my the route handler where the problem occurs

const knex = require('knex');
const JWT = require('jsonwebtoken');
const knexInstance = require('../knexConfig.js')

module.exports = async (request, h) => {
    console.log(`requested user ${request.auth.credentials.user}'s data !`);
    try {
        const user_data = await knexInstance('users').where('name', request.auth.credentials.user).first()
        if(user_data) {
            return user_data
        }
    }
    catch(e) {
        console.log(e)
    }


    return request.auth.credentials
};

and here is its configuration :

const Handler = require('./handler')
const Config = require('./config')
const Validate = require('./validate');


module.exports = {
    path: Config.route.url,
    method: Config.route.method,
    config: {
        handler: Handler,
        // validate: Validate,
        auth: 'jwt',
        description: 'Register',
        notes: 'Some note',
        tags: ['api']
    },
}

and here is how i request it from my client :

 await axios.get('http://localhost:4545/user', {
      headers: {
        Authorization: `Bearer ${accessToken}`
      }
    })
    .then(response => {
      console.log(response.data);
    })
    .catch(error => {
      console.error('Error:', error);
    });

the routes which dont require jwt authorization are working perfect !

Upvotes: 0

Views: 81

Answers (0)

Related Questions