Before you start
- Node.js
- Go
- Deploy an instance of the OpenFGA server, and have ready the values for your setup: FGA_STORE_ID, FGA_API_URL and, if needed, FGA_API_TOKEN.
- You have installed the OpenFGA SDK.
- You have configured the authorization model and updated the relationship tuples.
- You know how to perform a Check.
- You have loaded
FGA_API_URLandFGA_STORE_IDas environment variables.
Step by step
Assume that you want to have a web service fordocuments using one of the frameworks mentioned above. The service will authenticate users via JWT tokens, which contain the user ID.
Assume that you want to provide a route GET /read/{document} to return documents depending on whether the authenticated user has access to it.
01. Install and setup framework
The first step is to install the framework.- Node.js
- Go
For the context of this example, we will use the Fastify framework. For that we need to install the following packages:Using yarn:Next, we setup the web service with the
- the
fastifypackage that provides the framework itself - the
fastify-pluginpackage that allows integrating plugins with Fastify - the
fastify-jwtpackage for processing JWT tokens
GET /read/{document} route in file app.js.02. Authenticate and get user ID
Before we can call OpenFGA to protect the/read/{document} route, we need to validate the user’s JWT.
- Node.js
- Go
The Then, use the Finally, update
fastify-jwt package allows validation of JWT tokens, as well as providing access to the user’s identity.In jwt-authenticate.js:preValidation hook of a route to protect it and access the user information inside the JWT:In route-read.js:app.js to register the newly added hooks.03. Integrate the OpenFGA check API into the service
- Node.js
- Go
First, we will create a decorator Next, we will create a decorator called We can now update the Finally, we will register the new hooks in
preauthorize to parse the incoming HTTP method as well as name of the document, and set the appropriate relation and object that we will call Check on.In preauthorize.js:authorize. This decorator will invoke the Check API to see if the user has a relationship with the specified document.In authorize.js:GET /read/{document} route to check for user permissions.In route-read.js:app.js:Related Sections
Take a look at the following sections for examples that you can try when integrating with SDK.Entitlements
Modeling Entitlements for a System in OpenFGA.
IoT
Modeling Fine-Grained Authorization for an IoT Security Camera System with OpenFGA.
Slack
Modeling Authorization for Slack with OpenFGA.