Hapi Micro Auth Plugin

4.0.1 · abandoned · verified Wed Apr 22

hapi-micro-auth is a Hapi plugin designed to integrate with the micro-auth authentication service, exposing its functionalities as an authentication provider within a Hapi server. It handles session management, user retrieval, and authentication routes by proxying requests to a configured micro-auth instance. The current stable version is 4.0.1. The project appears to have an inactive release cadence, with its last major update (4.0.0) in late 2020. Key differentiators include its tight coupling with the firstandthird/micro-auth service, providing a specific solution for projects already leveraging that authentication backend. It offers methods to interact with user data, session updates, and metadata management via `server.microauth` methods.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a Hapi server, register the hapi-micro-auth plugin with essential configurations, and define a protected route that uses the 'microauth' strategy to retrieve user credentials.

import Hapi from '@hapi/hapi';
import hapiMicroAuth from 'hapi-micro-auth';

const init = async () => {
  const server = Hapi.server({
    port: 3000,
    host: 'localhost'
  });

  await server.register({
    plugin: hapiMicroAuth,
    options: {
      host: process.env.MICRO_AUTH_HOST ?? 'http://localhost:8081/auth', // URL to micro-auth service
      routes: true, // Enable default auth routes (e.g., /login, /logout)
      strategy: {
        name: 'microauth',
        mode: 'required' // 'required', 'optional', 'try'
      },
      cookie: {
        name: 'auth_session',
        isSecure: process.env.NODE_ENV === 'production',
        ttl: 12960000000 // 150 days
      }
    }
  });

  server.route({
    method: 'GET',
    path: '/me',
    handler: async (request, h) => {
      try {
        // Assuming 'microauth' is the strategy name from plugin options
        const user = request.auth.credentials;
        if (!user) {
          return h.response('Not authenticated').code(401);
        }
        // Example of using a plugin method
        const fullUser = await server.microauth.getMe(user.token);
        return fullUser;
      } catch (error) {
        console.error('Error fetching user:', error);
        return h.response('Internal Server Error').code(500);
      }
    },
    options: {
      auth: 'microauth' // Apply the authentication strategy
    }
  });

  await server.start();
  console.log(`Server running on ${server.info.uri}`);
};

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

init();

view raw JSON →