Keycloak Node.js Adapter

repository·main·Indexed 20 days ago

https://github.com/keycloak/keycloak-nodejs-connect

A deprecated middleware module for integrating Node.js applications using Connect-style middleware with Keycloak for authentication and authorization. It provides the Keycloak class for configuration, middleware for Express apps, and methods like keycloak.protect() for role-based access control and keycloak.enforcer() for resource-based authorization via Keycloak Authorization Services.

Tokens
5K
Snippets
20
Records
22
Agent score
72%

What's inside keycloak-connect

  1. Important notice regarding Keycloak Node.js Adapter deprecation

    main

    Warning

    This package is deprecated and will be removed in the future. Keycloak will provide details regarding the removal date and recommended alternatives in due course. Users should plan to migrate to supported alternatives as they become available.

  2. Install and configure Keycloak middleware

    main

    To protect your application, install express and add the Keycloak middleware to your Express app using keycloak.middleware().

    Important: Proxy Configuration If your app is behind a proxy (e.g., Nginx, ELB) that terminates SSL, you must set trust proxy to true in Express to ensure correct redirect URIs are generated.

    const express = require('express');
    const app = express();
    
    // Required if running behind a proxy
    app.set('trust proxy', true);
    
    // Install Keycloak middleware
    app.use(keycloak.middleware());
    
    app.listen(3000);
    const express = require('express');
    const app = express();
    
    app.set('trust proxy', true);
    app.use(keycloak.middleware());
    
    app.listen(3000, function () {
        console.log('App listening on port 3000');
    });
  3. Get started with Keycloak Node.js Adapter examples

    main

    To begin using the adapter and see it in action, you should use the official quickstart repositories. The adapter is designed to make it simple to implement Node.js Connect-friendly applications that leverage Keycloak for authentication and authorization.

    Visit the [Keycloak QuickStarts](https://github.com/keycloak/keycloak-quickstarts) for runnable examples.
  4. Install the Keycloak Node.js adapter

    main

    To use the adapter, first create a client in the Keycloak Admin Console. Download the configuration by selecting Action -> Download adapter config, choosing Keycloak OIDC JSON as the format. Save this as keycloak.json in your project root.

    Then, initialize your project and add keycloak-connect to your dependencies:

    mkdir myapp && cd myapp
    npm init
    npm install keycloak-connect
  5. Start and configure Keycloak for the NodeJS example

    main

    Before running the NodeJS example, you must have a running Keycloak instance with the required realm imported. You can start Keycloak using Docker or a standard installation.

    Using Docker

    Run the following command to start Keycloak with default admin credentials:

    docker run -p 8080:8080 -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin jboss/keycloak

    Using Standard Installation

    Execute the standalone script from your Keycloak directory:

    /<Path-To-Keycloak>/bin/standalone.sh

    Configure the Realm

    1. Open the Keycloak admin console.
    2. Click on Add Realm.
    3. Click on import 'Select file'.
    4. Select the nodejs-example-realm.json file (provided in the repository).
    5. Click Create.
  6. Build the Keycloak Node.js adapter from source

    main

    To build the adapter from source, ensure you have Node.js 8 or newer and Git installed. Clone the repository, navigate to the directory, and run npm install to install the adapter and its dependencies.

    # Check prerequisites
    node --version
    git --version
    
    # Clone and build
    git clone https://github.com/keycloak/keycloak-nodejs-connect.git
    cd keycloak-nodejs-connect
    npm install
  7. Run the Basic NodeJS Example

    main

    To run the example project locally, follow these steps to link the keycloak-connect library and start the application:

    1. Link the local adapter: From the example directory, link the parent directory containing the keycloak-connect source code:
      npm link ../
    
    2. **Install dependencies**: Install the required Node.js packages:
       ```bash
    npm install
    1. Start the application:
      npm start
    
    4. **Access the app**: Open your browser at `http://localhost:3000/`. You can log in using the following credentials:
       - **Username**: `user`
       - **Password**: `password`
    
    npm link ../
    npm install
    npm start
  8. Best practices for writing new tests

    main

    When writing new tests, follow the existing patterns established in the test folder.

    • Approach: Follow the existing testing methodology used throughout the repository.
    • Strategy: Depending on the feature or enhancement, you may choose to add to an existing test or write a new one from scratch.
    • Recommendation: If writing a new test from scratch, find an existing test that is similar to your use case and use it as a template/basis.
  9. Instantiate the Keycloak adapter

    main

    To use the Keycloak adapter, create a new instance of Keycloak. You can provide a config object for adapter-specific settings and an optional keycloakConfig object for Keycloak-specific settings. If keycloakConfig is not provided, the adapter will automatically attempt to load configuration from a keycloak.json file located alongside your application.

    Configuration Options

    config (Object):

    • store: A custom session-store implementation. Using a session-based store is recommended for better control from the Keycloak console.
    • cookies: Set to true to use cookies as your authentication store. Note: This requires a cookie parser (like cookie-parser in Express.js) to be present in your middleware stack. You cannot use both store and cookies simultaneously.
    • scope: A custom scope string.
    • idpHint: An Identity Provider hint.

    keycloakConfig (Object):

    • Keycloak-specific configuration (typically loaded from keycloak.json).
    // Example using default keycloak.json
    var keycloak = new Keycloak();
    
    // Example with custom configuration
    var keycloak = new Keycloak({
      cookies: true,
      scope: 'email profile'
    }, {
      realmUrl: 'https://keycloak.example.com/auth',
      clientId: 'my-app'
    });