DEV Community

Cover image for Role-based Access Control in Golang with jwt-go
Benson Macharia
Benson Macharia

Posted on

Role-based Access Control in Golang with jwt-go

As a security engineer, what's the first thing you check when testing a web or mobile application? Access control misconfigurations must be at the top of your list if you like going for the low hanging fruits first.

Surprisingly, access control is one of the components that application developers think will be simple, but ends up taking much of their time with no end user value, and even worse ends being poorly done, tremendous exposing the application to security risks. It is no coincidence that Authentication and Authorization related issues take the first two positions in the OWASP Top 10 - 2023 list of common API security risks.

For this reason, in this article I am going to illustrate the application of Role-based Access Control; a simple and yet secure access control approach for enterprise APIs.

Role-based Access Control (RBAC)
Role-based Access Control is a mechanism that restricts access to an information system based on user job functions or roles. Access to data is restricted through permissions and privileges that are attached to different user roles.

Let's Build
By the end of this article we are going build a simple room booking API with Go that will allow visitors to view available rooms as well as register, login and book rooms. There will also be an administrator who will have the permissions map user to permissions as well as add and update rooms information.

Image description

Prerequisites

  • Basic knowledge of Go
  • Patience 😄

Source Code

$ git clone https://github.com/bensonmacharia/jwt-go-rbac.git
Enter fullscreen mode Exit fullscreen mode

Step 1: Setting up the environment

  • Get your favourite IDE, mine is vscode
  • Download and install Go
  • Confirm installed go version
$ go version    
go version go1.19.4 darwin/arm64
Enter fullscreen mode Exit fullscreen mode
// confirm installation by checking version
$ mysql --version
mysql  Ver 8.0.32 for macos12.6 on arm64 (Homebrew)

// test connection
$ mysql -u bmacharia -p
Enter password: 
mysql>
Enter fullscreen mode Exit fullscreen mode
  • Create a database
// create database
$ mysql> CREATE DATABASE jwt_go_rbac;
Query OK, 1 row affected (0.07 sec)

// confirm database creation
$ mysql> show databases;
+-------------------------+
| Database                |
+-------------------------+             |
| information_schema      |
| jwt_go_rbac             |
| mysql                   |
| performance_schema      |
| sys                     |
+-------------------------+
5 rows in set (0.01 sec)
Enter fullscreen mode Exit fullscreen mode

Step 2: Setting up the project

  • Create project folder and initialise go project
$ mkdir jwt-go-rbac                                                                
$ cd jwt-go-rbac            
$ go mod init bmacharia/jwt-go-rbac            
go: creating new go.mod: module bmacharia/jwt-go-rbac
Enter fullscreen mode Exit fullscreen mode
  • Create the main.go and .env files
// main go application file
$ touch main.go

// environment variables configuration file
$ touch .env
Enter fullscreen mode Exit fullscreen mode
  • Open the project in your IDE and edit the .env file as below

Step 3: Configure the database connection

  • Install required packages
// package to load .env file
$ go get github.com/joho/godotenv
// package to allow connection to MySQL database
$ go get -u gorm.io/driver/mysql
// a simple Go HTTP web framework
$ go get github.com/gin-gonic/gin
// ORM (Object Relational Mapping) library for Go
$ go get -u gorm.io/gorm
// jwt-go package
$ go get -u github.com/golang-jwt/jwt/v5
Enter fullscreen mode Exit fullscreen mode
  • Create a database connection file
// create a database folder and a file inside it
$ mkdir database
$ touch database/database.go
Enter fullscreen mode Exit fullscreen mode
  • Edit the database.go file as below. We are using GORM to initiate a connection to MySQL database.
  • Edit the main.go file to test database connection. In this file we are loading the .env file, database connection and starting the gin web server on port 8000

  • Test database connection by running the go run command

$ go run main.go
2023/05/01 23:25:13 .env file loaded successfully
2023/05/01 23:25:13 `Successfully connected to the database
[GIN-debug] Listening and serving HTTP on :8000
Enter fullscreen mode Exit fullscreen mode

Step 4: Create database models

  • Create the user and role models. The user model defines the user object details as well as user properties in the database. On the other hand, the role model details properties about a role to be assigned to each user.
// create a user.go file inside the model directory
$ mkdir model
$ touch model/user.go
$ touch model/role.go
Enter fullscreen mode Exit fullscreen mode
  • model/user.go
  • model/role.go
  • Run database migrations
//edit main.go file to add automigration script
...
// run database migrations and add seed data
func loadDatabase() {
    database.InitDb()
    database.Db.AutoMigrate(&model.Role{})
    database.Db.AutoMigrate(&model.User{})
    seedData()
}

// load seed data into the database
func seedData() {
    var roles = []model.Role{{Name: "admin", Description: "Administrator role"}, {Name: "customer", Description: "Authenticated customer role"}, {Name: "anonymous", Description: "Unauthenticated customer role"}}
    var user = []model.User{{Username: os.Getenv("ADMIN_USERNAME"), Email: os.Getenv("ADMIN_EMAIL"), Password: os.Getenv("ADMIN_PASSWORD"), RoleID: 1}}
    database.Db.Save(&roles)
    database.Db.Save(&user)
}
// run migration
$ go run main.go
..
Enter fullscreen mode Exit fullscreen mode
  • Confirm that users and roles tables have been created
mysql> show tables;
+-----------------------+
| Tables_in_jwt_go_rbac |
+-----------------------+
| roles                 |
| users                 |
+-----------------------+
2 rows in set (0.01 sec)
mysql> desc users;
mysql> desc roles;
mysql> select * from roles;
mysql> select * from users;
Enter fullscreen mode Exit fullscreen mode
  • Create models for user registration, login and update
$ touch model/register.go
$ touch model/login.go
$ touch model/update.go
Enter fullscreen mode Exit fullscreen mode
  • model/register.go
  • model/login.go
  • model/update.go

Step 5: Create controllers to interact with database content

  • Create the role and user controller files
$ touch controller/role.go
$ touch controller/user.go
Enter fullscreen mode Exit fullscreen mode
  • controller/role.go
  • controller/user.go
  • Add registration and login routes
// edit main.go
func serveApplication() {
    router := gin.Default()
    authRoutes := router.Group("/auth/user")
        // registration route
    authRoutes.POST("/register", controller.Register)
        // login route
    authRoutes.POST("/login", controller.Login)

    router.Run(":8000")
    fmt.Println("Server running on port 8000")
}
Enter fullscreen mode Exit fullscreen mode
  • Test user registration and login
// run the application
$ go run main.go
// register user
$ curl -X POST http://localhost:8000/auth/user/register \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -d '{"username": "test","email":"test@bmacharia.com","password":"super^Secret!007"}'
// test user login
$ curl -X POST http://localhost:8000/auth/user/login \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -d '{"username": "test","password":"super^Secret!007"}' 
Enter fullscreen mode Exit fullscreen mode

Step 6. Add JWT utility for token creation and validation

  • To create a secure Role-based authentication scheme, we need to generate a unique token when the user authenticates. This is then used to track their assigned role as they consume the availed resources. In this project we are going to use the jwt-go package to generate a JWT token that will encapsulate the user details, assigned role and permissions.
  • Create the JWT utility files
// create a util directory
$ mkdir util
$ touch jwt.go
$ touch jwtAuth.go
Enter fullscreen mode Exit fullscreen mode
  • jwt.go
  • jwtAuth.go

  • Add token to user login response

// edit user controller and append 
func Login(context *gin.Context) {
     jwt, err := util.GenerateJWT(user)
     if err != nil {
        context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    context.JSON(http.StatusOK, gin.H{"token": jwt, "username": input.Username, "message": "Successfully logged in"})
}
Enter fullscreen mode Exit fullscreen mode
  • Add admin functions routes
// edit main.go
func serveApplication() {
        adminRoutes := router.Group("/admin")
    adminRoutes.Use(util.JWTAuth())
    adminRoutes.GET("/users", controller.GetUsers)
    adminRoutes.GET("/user/:id", controller.GetUser)
    adminRoutes.PUT("/user/:id", controller.UpdateUser)
    adminRoutes.POST("/user/role", controller.CreateRole)
    adminRoutes.GET("/user/roles", controller.GetRoles)
    adminRoutes.PUT("/user/role/:id", controller.UpdateRole)
}
Enter fullscreen mode Exit fullscreen mode

Step 7: Run and Test Admin Funtions

  • Run API
$  go run main.go
Enter fullscreen mode Exit fullscreen mode
  • Admin login
// admin user login
$ curl -X POST http://localhost:8000/auth/user/login \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -d '{"username": "test","password":"super^Secret!007"}' 
Enter fullscreen mode Exit fullscreen mode
  • Get All Users
// use admin token from login response
$ curl -X GET http://localhost:8000/admin/users \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlYXQiOjE2ODQ0NDc1ODQsImlhdCI6MTY4NDQ0NTc4NCwiaWQiOjEsInJvbGUiOjF9.CKQf2GggCP1cnGqfTp_2R77Q7GsQBX_dxf5PSLEbTx8" \
     -d '{"username": "test","password":"super^Secret!007"}'
Enter fullscreen mode Exit fullscreen mode
  • Get User by ID
$ curl -X GET http://localhost:8000/admin/user/1 \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlYXQiOjE2ODQ0NDc1ODQsImlhdCI6MTY4NDQ0NTc4NCwiaWQiOjEsInJvbGUiOjF9.CKQf2GggCP1cnGqfTp_2R77Q7GsQBX_dxf5PSLEbTx8"
Enter fullscreen mode Exit fullscreen mode
  • Update User
$ curl -X PUT http://localhost:8000/admin/user/2 \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlYXQiOjE2ODQ0NDc1ODQsImlhdCI6MTY4NDQ0NTc4NCwiaWQiOjEsInJvbGUiOjF9.CKQf2GggCP1cnGqfTp_2R77Q7GsQBX_dxf5PSLEbTx8" \
     -d '{"username": "test","email":"test@gmail.com","role_id":"2"}'
Enter fullscreen mode Exit fullscreen mode
  • Create Role
$ curl -X POST http://localhost:8000/admin/user/role \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlYXQiOjE2ODQ0NDc1ODQsImlhdCI6MTY4NDQ0NTc4NCwiaWQiOjEsInJvbGUiOjF9.CKQf2GggCP1cnGqfTp_2R77Q7GsQBX_dxf5PSLEbTx8" \
     -d '{"name": "testing","description":"Test user role"}'
Enter fullscreen mode Exit fullscreen mode
  • Get All Roles
$ curl -X GET http://localhost:8000/admin/user/roles \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlYXQiOjE2ODQ0NDc1ODQsImlhdCI6MTY4NDQ0NTc4NCwiaWQiOjEsInJvbGUiOjF9.CKQf2GggCP1cnGqfTp_2R77Q7GsQBX_dxf5PSLEbTx8"
Enter fullscreen mode Exit fullscreen mode
  • Update Role
$ curl -X PUT http://localhost:8000/admin/user/role/4 \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlYXQiOjE2ODQ0NDc1ODQsImlhdCI6MTY4NDQ0NTc4NCwiaWQiOjEsInJvbGUiOjF9.CKQf2GggCP1cnGqfTp_2R77Q7GsQBX_dxf5PSLEbTx8" \
     -d '{"name":"accountant","description":"Accountant user role"}'
Enter fullscreen mode Exit fullscreen mode
  • Add Room
$ curl -X POST http://localhost:8000/admin/room/add \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlYXQiOjE2ODQ0NDc1ODQsImlhdCI6MTY4NDQ0NTc4NCwiaWQiOjEsInJvbGUiOjF9.CKQf2GggCP1cnGqfTp_2R77Q7GsQBX_dxf5PSLEbTx8" \
     -d '{"name": "Room 9","location":"Second Floor"}'
Enter fullscreen mode Exit fullscreen mode
  • List all Rooms
$ curl -X GET http://localhost:8000/api/view/rooms \
     -H "Content-Type: application/json" \
     -H "Accept: application/json"
Enter fullscreen mode Exit fullscreen mode
  • Get Room by ID
$ curl -X GET http://localhost:8000/api/view/room/3 \
     -H "Content-Type: application/json" \
     -H "Accept: application/json"
Enter fullscreen mode Exit fullscreen mode

Step 8: Test the room booking service

  • Book a Room
$ curl -X POST http://localhost:8000/api/room/book \
     -H "Content-Type: application/json" \
     -H "Accept: application/json" \
     -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlYXQiOjE2ODUyMjk0MDEsImlhdCI6MTY4NTIyNzYwMSwiaWQiOjI0LCJyb2xlIjoyfQ.h8R51DA5N_xeCa8xR1HLeOo4JTmIGjUp3oMPJLuBv3g" \
     -d '{"room_id": 3}'
Enter fullscreen mode Exit fullscreen mode
  • List all Bookings
$ curl -X GET http://localhost:8000/admin/room/bookings \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlYXQiOjE2ODcyOTkyMTAsImlhdCI6MTY4NzI5NzQxMCwiaWQiOjEsInJvbGUiOjF9.3oztz8EgE-l3byKWzCI760FE-BmRY7B-BohnYydDElc" \
     -H "Accept: application/json"
Enter fullscreen mode Exit fullscreen mode
  • List all User Bookings
$ curl -X GET http://localhost:8000/api/rooms/booked \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlYXQiOjE2ODUyMjk0MDEsImlhdCI6MTY4NTIyNzYwMSwiaWQiOjI0LCJyb2xlIjoyfQ.h8R51DA5N_xeCa8xR1HLeOo4JTmIGjUp3oMPJLuBv3g" \
     -H "Accept: application/json"
Enter fullscreen mode Exit fullscreen mode

Winding up
RBAC presents the simplest form of access control that can help prevent unauthorised access to data. This facilitates compliance to various regulatory and compliance requirements especially those related to data protection, privacy and system access. With RBAC, it's also easy to maintain an audit trail of all user activities which can significantly help speed up incident response process.

Let's connect
LinkedIn
Twitter
Blog

Top comments (8)

Collapse
 
alfiedang3r profile image
alfie.danger • Edited

how do you generate the JWT token for the .env file?

Collapse
 
bensonmacharia profile image
Benson Macharia

Hello alfie,
The JWT_PRIVATE_KEY="<>" in the .env file should be a random string that is being used as a secret to generate the JWT token. It should be long enough from 12 characters and contain a mixture of special characters and alphanumeric to ensure that the generated JWT token is secure. You can for instance make use of the LastPass random string generator here - lastpass.com/features/password-gen...

Collapse
 
arthasmx profile image
Arthas MX

AFAI-understand, you have to do it manually; think it's like a salted logic or some...hope Benson has time to tell us about it

Collapse
 
abdulrahmandaudmiraj profile image
Abdulrahman Daud Miraj

This is really good article

Collapse
 
bensonmacharia profile image
Benson Macharia

Much appreciation

Collapse
 
munz profile image
Munz

What should I do if I want to change my password

Collapse
 
diofanto33 profile image
diofanto33

Hello,

Very good contribution !

...Is it possible that when registering a user, you are saving the password without encryption?

Thank you very much!

Collapse
 
klrfl profile image
Efraim Munthe

You can, just insert the password in plain text to the database just like any other data, but as you might have probably knew this is so so very unsafe. I would advise you
against doing that.