This example demonstrates a boilerplate setup for a Go Fiber application that uses JWT for authentication.
This project provides a starting point for building a web application with user authentication using JWT. It leverages Fiber for the web framework and GORM for ORM.
-
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/auth-jwt
-
Set the environment variables in a
.env
file:DB_PORT=5432 DB_USER=example_user DB_PASSWORD=example_password DB_NAME=example_db SECRET=example_secret
-
Install the dependencies:
go mod download
-
Run the application:
go run main.go
The API should now be running on http://localhost:3000
.
You can manage the database via psql
with the following command:
psql -U <DB_USER> -d <DB_NAME> -h localhost -p <DB_PORT>
Replace <DB_USER>
, <DB_NAME>
, and <DB_PORT>
with the values from your .env
file.
The following endpoints are available in the API:
- POST /api/auth/register: Register a new user.
- POST /api/auth/login: Authenticate a user and return a JWT.
- GET /api/user/:id: Get a user (requires a valid JWT).
- POST /api/user: Create a new user.
- PATCH /api/user/:id: Update a user (requires a valid JWT).
- DELETE /api/user/:id: Delete a user (requires a valid JWT).
- GET /api/product: Get all products.
- GET /api/product/:id: Get a product.
- POST /api/product: Create a new product (requires a valid JWT).
- DELETE /api/product/:id: Delete a product (requires a valid JWT).
-
Register a new user:
curl -X POST http://localhost:3000/api/auth/register -d '{"username":"testuser", "password":"testpassword", "email":"test@example.com"}' -H "Content-Type: application/json"
-
Login to get a JWT:
curl -X POST http://localhost:3000/api/auth/login -d '{"username":"testuser", "password":"testpassword"}' -H "Content-Type: application/json"
-
Access a protected route:
curl -H "Authorization: Bearer <JWT>" http://localhost:3000/api/user/1
Replace <JWT>
with the token received from the login endpoint.
This example provides a basic setup for a Go Fiber application with JWT authentication. It can be extended and customized further to fit the needs of more complex applications.