Add fine-grained authorization to a Gin app
Build a Gin API in Go for a blogging platform that registers users in Permit.io and allows only users with the Author role to create posts. This tutorial is for Go backend developers who want to enforce Permit.io policies from Gin routes and middleware.
When you finish, your Gin app has two endpoints:
| Endpoint | What it does |
|---|---|
POST /register | Syncs a user to Permit.io and assigns the user the Reader role in the default tenant |
POST /posts | Runs middleware that calls permitClient.Check() and returns 403 unless the user in the X-User header has permission to create a Post |
Prerequisites
- A Permit.io account. See Create a Permit.io account.
- Go and a Go module for your app. The app uses Gin.
- Node.js and npm, to install the Permit CLI.
- Docker, to run the policy decision point (PDP) container.
1. Configure the policy in Permit
Create the blogging platform policy with the Permit CLI. If your environment already has a policy with a Post resource and an Author role that can create posts, skip to 2. Get your API key.
Install the Permit CLI
The Permit CLI creates policies and runs the PDP from your terminal. Install the CLI with npm:
npm install -g @permitio/cli
Run permit to confirm that the CLI is installed.
Sign in with the Permit CLI
Authenticate the CLI with your Permit.io account:
permit login
The command opens a browser window where you sign in. After you sign in, the CLI uses your default environment. To use a different environment, run permit env select and choose the environment.
Apply the blogging platform template
Permit CLI templates create a policy with predefined resources, roles, and rules. To see the available templates, run permit env template list. The template source files are in the Permit CLI repository.

Apply the blogging-platform template to your environment:
permit env template apply --template blogging-platform
The CLI prints a success message when the template is applied.
Review the policy in the Policy Editor
In the Permit dashboard, select your project and open the Policy screen.

The blogging-platform template creates:
| Policy element | What the template defines |
|---|---|
| Resources | Post (with a premium boolean attribute) and Comment, each with create, read, update, and delete actions |
| Roles | Admin (all actions), Author (create and read posts, read comments), Reader (create and read comments), and Premium Reader (read posts and comments) |
| Relationship | A Post is the parent of its Comment instances. An Author of a post instance becomes a Moderator of the comments on that post. This rule is relationship-based access control (ReBAC). |
| Resource set | Free Post contains posts where premium is false. Readers can read free posts. This rule is attribute-based access control (ABAC). |
This tutorial uses one rule from the policy: the Author role can create a Post, and the Reader role cannot. To change which role can perform an action, check or clear the box in the Policy Editor.
2. Get your API key
Your Gin app and the PDP authenticate with Permit.io with your environment API key. Copy the API key of the environment where you applied the template. See Get your API key.
Anyone with the environment API key can change that environment's policy through the Permit API. Load the key from an environment variable, and don't commit it.
3. Run the PDP
The PDP evaluates each permission check against your policy. Start a PDP container with the Permit CLI:
permit pdp run
The command starts the PDP in Docker and prints the container ID and name. The PDP listens on port 7766, so your app connects to it at http://localhost:7766.

The Free Post resource set is an ABAC rule, and the Cloud PDP doesn't evaluate ABAC rules, so run the container PDP for this policy. To run the container with docker run instead, or to check that the PDP is healthy, see Run the PDP.
4. Build the Gin app
All the Go code in this section goes in one file, main.go, in your Go module.
Install the Go SDK
In your Go module directory, install the Permit Go SDK:
go get github.com/permitio/permit-golang
The code in this tutorial also imports Gin (github.com/gin-gonic/gin), zap (go.uber.org/zap), and godotenv (github.com/joho/godotenv). After you add the code, run go mod tidy to download these modules. For all SDK options, see Check permissions with the Go SDK.
Declare the imports and the Permit client variable
Add the imports, a package-level permitClient variable, and the UserIn struct to main.go:
package main
import (
"context"
"log"
"net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"github.com/permitio/permit-golang/pkg/config"
"github.com/permitio/permit-golang/pkg/enforcement"
"github.com/permitio/permit-golang/pkg/models"
"github.com/permitio/permit-golang/pkg/permit"
"go.uber.org/zap"
)
var permitClient *permit.Client
// struct for user input
type UserIn struct {
Email string `json:"email" binding:"required,email"`
FirstName string `json:"first_name" binding:"required"`
LastName string `json:"last_name" binding:"required"`
}
The UserIn struct binds the JSON body of a POST /register request. Gin's binding tags reject a request without a valid email, first_name, or last_name.
Initialize the Permit client and define the routes
Add the main function to main.go:
// main.go
func main() {
_ = godotenv.Load()
apiKey := os.Getenv("PERMIT_API_KEY")
pdpURL := os.Getenv("PDP_URL")
permitClient = permit.NewPermit(
config.NewConfigBuilder(apiKey).
WithLogger(zap.NewExample()).
WithPdpUrl(pdpURL).
Build(),
)
router := gin.Default()
// health check endpoint
router.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Hello, Gin with Permit!"})
})
// register new user
router.POST("/register", registerUserHandler)
// protected endpoint: only authors can create posts
router.POST("/posts", CreatePostMiddleware(), func(c *gin.Context) {
c.JSON(http.StatusCreated, gin.H{
"message": "Post created successfully",
})
})
log.Println("Server running on http://localhost:8000")
router.Run(":8000")
}
The main function loads a .env file with godotenv, if one exists, and creates the Permit client from two environment variables:
| Variable | Value |
|---|---|
PERMIT_API_KEY | Your environment API key from 2. Get your API key |
PDP_URL | The PDP address from 3. Run the PDP: http://localhost:7766 |
The function then registers three routes on port 8000:
| Route | Handler |
|---|---|
GET / | Returns a health message |
POST /register | registerUserHandler |
POST /posts | CreatePostMiddleware(), then a handler that returns 201 with "Post created successfully" |
Add the /register handler
Add registerUserHandler to main.go. The handler syncs the user to Permit.io with permitClient.Api.Users.SyncUser(), then assigns the user the Reader role in the default tenant with permitClient.Api.Users.AssignRole().
// handler for /register endpoint
func registerUserHandler(c *gin.Context) {
var user UserIn
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
createUser := models.NewUserCreate(user.Email)
createUser.SetFirstName(user.FirstName)
createUser.SetLastName(user.LastName)
createUser.SetEmail(user.Email)
newUser, err := permitClient.Api.Users.SyncUser(context.Background(), *createUser)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to sync user"})
return
}
if newUser == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "User not found"})
return
}
// Assign the Reader role to the user in the 'default' tenant
roleAssignment, err := permitClient.Api.Users.AssignRole(context.Background(), user.Email, "Reader", "default")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to assign role"})
return
}
// ... proceed with your app's registration logic
// For example, create a user record in your database here
c.JSON(http.StatusCreated, gin.H{
"message": "User registered and role assigned",
"user": newUser,
"role_assignment": roleAssignment,
})
}
The user's email address is the user key in Permit.io. The /posts middleware passes the same key to permitClient.Check().
Protect the /posts route with middleware
Add CreatePostMiddleware to main.go. The middleware reads the user key from the X-User header and asks the PDP whether that user can create a Post:
// middleware for checking if the user can create a post
func CreatePostMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
user := c.GetHeader("X-User")
if user == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing permission header: X-User"})
c.Abort()
return
}
action := "create"
resource := "Post"
enfUser := enforcement.UserBuilder(user).Build()
enfResource := enforcement.ResourceBuilder(resource).Build()
permitted, err := permitClient.Check(enfUser, enforcement.Action(action), enfResource)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Permission check failed"})
c.Abort()
return
}
if !permitted {
c.JSON(http.StatusForbidden, gin.H{"message": "You are not authorized to create a post"})
c.Abort()
return
}
c.Next()
}
}
The middleware responds as follows:
| Condition | Response |
|---|---|
The X-User header is missing | 400 with "Missing permission header: X-User" |
| The PDP call fails | 500 with "Permission check failed" |
| The PDP denies the request | 403 with "You are not authorized to create a post" |
| The PDP allows the request | Gin runs the /posts handler, which returns 201 |
To protect other routes, such as commenting or editing, change the action and resource values.
In a production app, take the user key from your authenticated session. This example reads the user key from the X-User header so that you can test the route with curl.
Start the Gin app
Set the environment variables and start the app, replacing <YOUR_API_KEY> with your API key:
export PERMIT_API_KEY=<YOUR_API_KEY>
export PDP_URL=http://localhost:7766
go run main.go
The app listens on http://localhost:8000.
5. Test the permission check
Register two users, give one of them the Author role, and confirm that the PDP allows only that user to create a post.
Register two users
In a second terminal, register John and Emma:
curl -X POST http://localhost:8000/register \
-H "Content-Type: application/json" \
-d '{"email": "john@example.com", "first_name": "John", "last_name": "Doe"}'
curl -X POST http://localhost:8000/register \
-H "Content-Type: application/json" \
-d '{"email": "emma@example.com", "first_name": "Emma", "last_name": "Den"}'
Each request returns HTTP 201 with "message": "User registered and role assigned", the synced user under user, and the role assignment under role_assignment, with "role": "Reader" and "tenant": "default".
Assign John the Author role
Both users have the Reader role, which can't create posts. Give John the Author role in the Permit dashboard:
- Open the Directory screen and select
john@example.comto open the Edit User panel. - Under Permissions Per Tenant, select the Default Tenant.
- In Top Level Access, add the Author role.
- Click Save.

For other ways to assign roles, including the API and SDK, see Sync users.
Check that John can create a post and Emma can't
Send a POST /posts request for John:
curl -X POST http://localhost:8000/posts \
-H "X-User: john@example.com"
The PDP allows the request because John has the Author role. The app returns HTTP 201 with {"message":"Post created successfully"}.
Send the same request for Emma:
curl -X POST http://localhost:8000/posts \
-H "X-User: emma@example.com"
The PDP denies the request because Emma has only the Reader role. The app returns HTTP 403 with {"message":"You are not authorized to create a post"}.
Each check also appears in the Audit Log screen of the Permit dashboard, with the user, action, resource, and decision.
Next steps
- Check permissions with the Go SDK: SDK installation, configuration, and more permission check examples.
- Check permissions with permit.check(): check against tenants, resource instances, and attributes.
- Build RBAC policies: create roles and permissions for your own resources.
- Deploy the PDP to production: run the PDP next to your services.