How to set up and integrate Open Policy Agent (OPA) with Express.js in a TypeScript project
Accessing data and functionality requires checking two different things. First you need to establish the identity of the user. The user may be another software that uses your API. Once you have established identity you need to check the permissions of the validated identity.
Establishing identity is also called authentication, often shortened to just “authN”. Determining whether a given access is granted or denied is typically called authorization, often shortened to “authZ”.
In this article I’ll focus on authZ. Future articles will address authN, e.g. by using Keycloak as an identity provider (IDP). For authZ we will use Open Policy Agent (OPA) in this article. I like OPA because it is one of the Cloud Native Computing Foundation (CNCF) projects.
We will explore the following topics:
- How to use OPA from the command line during development
- How to set up OPA as a demon in the dev container
- How to write a simple policy file
- How to integrate authZ in the request pipeline of express.js
The full source code is available at https://github.com/RimuTec/open-policy-agent-2023 under the permissive MIT license.
OPA on the Command Line in the Dev Container
OPA can be used in a variety of ways. In this article we will investigate authorizing API calls, and more specifically how to protect a RESTful API. OPA can used in other ways as well. You can find out more at their official web site.
To make OPA available on the command line in our dev container, we need to add it to the Dockerfile which contains the instructions for Docker about how to create the container image.
In line 36 we set the work directory for Docker to a path that is accessible from any terminal. We are using “/usr/local/bin” which is a good choice for Linux-based containers (Note that all containers I use in my articles are Linux based.)