Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Configuring NGINX for OAuth/OpenID Connect SSO with Keycloak/Red Hat SSO

October 8, 2018
Siddhartha De
Related topics:
Security
Related products:
Red Hat Single sign-on

    In this article I cover configuring NGINX for OAuth-based Single Sign-On (SSO) using Keycloak/Red Hat SSO. This allows the use of OpenID Connect (OIDC) for federated identity. This configuration is helpful when NGINX is acting as a reverse-proxy server for a backend application server, for example, Tomcat or JBoss, where the authentication is to be performed by the web server.

    In this setup, Keycloak will act as an authorization server in OAuth-based SSO and NGINX will be the relaying party.  We will be using lua-resty-openidc, which is a library for NGINX implementing the OpenID Connect relying party (RP) and/or the OAuth 2.0 resource server (RS) functionality.

    Here's a diagram of an An OIDC-based authentication flow:

    OAuth-based authentication flow

    In order to install lua-resty-oidc, you need to install several other dependent modules on the NGINX server:

    • ngx_devel_kit
    • Lua
    • lua-nginx-module
    • lua-cjson.php
    • lua-resty-string

    Installation instructions

    1. First, we create a directory for keeping all the required packages and then we change the current working directory to the newly created directory. Here, I will execute all the commands as the root user; it is possible to execute them as a non-root user too, but some commands, for example, yum will not work for a non-root user and require additional steps to perform.
      # mkdir /tmp/nginx-lua
      # cd /tmp/nginx-lua
    2. Now, download the packages that are required:
      a. Download NGINX version 1.13.6 and extract it:

       

      # wget http://nginx.org/download/nginx-1.13.6.tar.gz
      # tar -zxvf nginx-1.13.6.tar.gz

      b. Download OpenSSL and extract it:

      # wget https://github.com/openssl/openssl/archive/OpenSSL_1_0_2g.tar.gz 
      # wget OpenSSL_1_1_0g.tar.gz

      c. Download lua-nginx-module and extract it:

      # wget https://github.com/openresty/lua-nginx-module/archive/v0.10.13.tar.gz 
      # tar -zxvf v0.10.13.tar.gz

      d. Download ngx_devel_kit and extract it:

      # wget https://github.com/simplresty/ngx_devel_kit/archive/v0.3.0.tar.gz
      # tar -zxvf v0.3.0.tar.gz

      e. Download Lua and extract it:

      # wget http://www.lua.org/ftp/lua-5.1.5.tar.gz
      # tar -zxvf lua-5.1.5.tar.gz

      f. Clone luaffib and install it using luarocks:

      # git clone https://github.com/facebookarchive/luaffifb
      # cd luaffifb
      # luarocks make
    3. Install the dependencies and packages required for lua-resty-oidc:
      a. We will first install Lua, so change the current working directory to lua-5.1.5 and then execute the installation:

       

      # cd lua-5.1.5
      # make linux test
      # make install
      # cd ..

      b. Install luarocks:

      # yum install luarocks

      c. Install all the Lua modules using luarocks:

      # luarocks install lua-cjson
      # luarocks install lua-resty-openidc

      d. After the Lua installation, export the PATH for LUA_LIB and LUA_INC:

      # export LUA_LIB=/usr/local/lib/lua/5.1/
      # export LUA_INC=/usr/local/include/

      e. Now, we need to install the development tools, for example, gcc, c++, etc.

      # yum group install "Development Tools"
      # yum install readline-devel

      f. Because we are going to do a binary installation of NGINX, we need to install pcre and zlib:

      # yum install pcre
      # yum install pcre-devel
      # yum install zlib
      # yum install zlib-devel
    4. Now, we can execute the installation of NGINX navigating into NGINX binary directory:
      # cd nginx-1.13.6
      # ./configure --prefix=/opt/nginx --with-http_ssl_module --with-ld-opt="-Wl,-rpath,/usr/local/lib/lua/5.1/" --add-module=/tmp/lua/ngx_devel_kit-0.3.0 --add-module=/tmp/lua/lua-nginx-module-0.10.13 --with-openssl=/tmp/lua/openssl-OpenSSL_1_0_2g
      # make -j2
      # make install
    5. After the successful execution of the installation command, NGINX will be installed in /opt/nginx.
    6. Create a directory called ssl in the directory /opt/nginx and generate a self-signed certificate:

       

      # mkdir /opt/nginx/ssl
      # cd /opt/nginx/ssl
      # openssl req -nodes -newkey rsa:2048 -keyout private.pem -out certificate.csr -subj "/C=IN/ST=WestBengal/L=Kolkata/O=Red Hat/OU=APS/CN=www.example.com"
      # openssl x509 -req -in certificate.csr -out certificate.pem -signkey private.pem

      Note: certificate.csr can be submitted to a CA vendor to get the certificate signed.

    7. Download Keycloak and extract it. Keycloak will be working as an Identity Provider and NGINX will act as a service provider.
      # wget https://downloads.jboss.org/keycloak/4.4.0.Final/keycloak-4.4.0.Final.zip
      # unzip  keycloak-4.4.0.Final.zip -d /opt/keycloak

    Configuring Keycloak and NGINX

    1. Create a user in the master realm and start Keycloak:
      # cd /opt/keycloak/keycloak-4.4.0.Final/bin
      # ./add-user-keycloak.sh -u admin -p admin@123 -r master      
      # ./standalone.sh -b www.example.com
    2. Create a new realm:
      a. Move the cursor near Master and click Add Realm.
      b. Provide a name for your realm and click Create.

       

      |

      Note: Creation of a new realm is not necessary; it possible to create a client in the master realm.

    3. Now, we need to create a client for NGINX. Click Client in the left panel and click the Create button:

    4. Select openid-connect as the client protocol and place the NGINX URL in the Root URL field:
    5. Set Access Type to confidential and click Save:
    6. Click Credentials and copy the secret for configuring NGINX later:
    7. Add the following line under the http block in nginx.conf:
      lua_package_path '~/lua/?.lua;;';
      resolver 8.8.8.8;
      # cache for discovery metadata documents
      lua_shared_dict discovery 1m;
      # cache for JWKs
      lua_shared_dict jwks 1m;
    8. Create the server in NGINX using something like the following:
       server {
             listen     80 default_server;
             server_name  www.example.com;
             root     /opt/nginx/html;
             access_by_lua '
               local opts = {
                 redirect_uri_path = "/redirect_uri",
                 accept_none_alg = true,
                 discovery = "http://www.example.com:8080/auth/realms/NGINX/.well-known/openid-configuration",
                 client_id = "nginx",
                 client_secret = "62d3b835-e3d1-4cec-a2f2-612f496bc6c3",
                 redirect_uri_scheme = "http",
                 logout_path = "/logout",
                 redirect_after_logout_uri = "http://www.example.com:8080/auth/realms/NGINX/protocol/openid-connect/logout?redirect_uri=http://www.example.com/",
                 redirect_after_logout_with_id_token_hint = false,
                 session_contents = {id_token=true}
               }
               -- call introspect for OAuth 2.0 Bearer Access Token validation
               local res, err = require("resty.openidc").authenticate(opts)
               if err then
                 ngx.status = 403
                 ngx.say(err)
                 ngx.exit(ngx.HTTP_FORBIDDEN)
               end
            ';
            # I disabled caching so the browser won't cache the site.
            expires           0;
            add_header        Cache-Control private;
            location / {
            }
            # redirect server error pages to the static page /40x.html
            #
            error_page 404 /404.html;
                location = /40x.html {
            }
            # redirect server error pages to the static page /50x.html
            #
            error_page 500 502 503 504 /50x.html;
                location = /50x.html {
            }
        }
    9. Validate the NGINX configuration:
      # cd /opt/nginx/sbin/
      # ./nginx -t
    10. After successful validation of the NGINX configuration, start the NGINX server:
      #./nginx

    Now, when you access the protected URL (www.example.com), you will be redirected to Keycloak at http://www.example.com:8080/auth/realms/NGINX/. After successful authentication, you will redirected back to the NGINX welcome page.

    Last updated: January 12, 2024

    Recent Posts

    • Protect data offloaded to GPU-accelerated environments with OpenShift sandboxed containers

    • Case study: Measuring energy efficiency on the x64 platform

    • How to prevent AI inference stack silent failures

    • Preventing GPU waste: A guide to JIT checkpointing with Kubeflow Trainer on OpenShift AI

    • How to manage TLS certificates used by OpenShift GitOps operator

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.