recipes/jwt

JWT

Using JSON Web Tokens (JWT) for authentication.

Fiber with JWT

Github StackBlitz

This example demonstrates how to use JSON Web Tokens (JWT) for authentication in a Fiber application.

Prerequisites

  • Go 1.27 or higher
  • Go modules
  • PostgreSQL. The product endpoints store their data there.

Setup

  1. Clone the repository:

    git clone https://github.com/gofiber/recipes.git
    cd recipes/jwt
  2. Install dependencies:

    go mod tidy
  3. Copy the sample environment file and fill it in. SECRET signs and verifies the tokens (for example openssl rand -hex 32). The application refuses to start without it, and it also needs a .env file to be present:

    cp .env.sample .env
    DB_HOST=localhost
    DB_PORT=5432
    DB_USER=postgres
    DB_PASSWORD=your_password
    DB_NAME=your_database
    SECRET=your_secret

Running the Application

  1. Run the application:

    go run main.go
  2. The server will start on http://localhost:3000.

Endpoints

MethodURLAuthDescription
GET/apinoStatus check
POST/api/auth/loginnoReturns a JWT for the demo user
GET/api/productnoLists all products
GET/api/product/:idnoGets a product by ID
POST/api/productJWTCreates a product
DELETE/api/product/:idJWTDeletes a product

The login handler accepts one hard-coded demo user, ender with the password ender. A real application checks the credentials against its own user store.

Example Requests

Login

curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"identity": "ender", "password": "ender"}'

The token is in the data field of the response.

Create a Product

curl -X POST http://localhost:3000/api/product \
  -H "Authorization: Bearer <your_jwt_token>" \
  -H "Content-Type: application/json" \
  -d '{"title": "Widget", "description": "A widget", "amount": 3}'

Get a Product

curl http://localhost:3000/api/product/1

A request to a protected route without a token answers 400, and one with an invalid or expired token answers 401.