This is a tutorial project that demonstrates how to implement JWT (JSON Web Token) authentication using the Go Fiber web framework.
- User registration
- User login
- Authenticated user retrieval
- User logout
- Go
- Go Fiber
- GORM (Object-Relational Mapping)
- MySQL
- JWT (JSON Web Tokens)
- Bcrypt (Password hashing)
The project is structured as follows:
.
├── controllers
│ └── authController.go
├── database
│ └── connection.go
├── main.go
├── models
│ └── user.go
└── routes
└── routes.go
main.go
: The entry point of the application, responsible for setting up the Fiber app, connecting to the database, and registering the routes.database/connection.go
: Handles the connection to the MySQL database using GORM.models/user.go
: Defines the User model and its properties.routes/routes.go
: Defines the application routes and maps them to the corresponding controllers.controllers/authController.go
: Implements the logic for user registration, login, user retrieval, and logout.
- Install Go and set up your development environment.
- Install the required dependencies:
- Go Fiber:
go get github.com/gofiber/fiber/v2
- GORM:
go get gorm.io/gorm
andgo get gorm.io/driver/mysql
- JWT:
go get github.com/golang-jwt/jwt/v5
- Bcrypt:
go get golang.org/x/crypto/bcrypt
- Go Fiber:
- Create a MySQL database named
go_auth
. - Update the database connection details in
database/connection.go
to match your MySQL configuration. - Run the application:
go run main.go
- The application will start running on
http:https://localhost:8000
.
POST /api/register
: Register a new user.POST /api/login
: Log in a user and receive a JWT cookie.GET /api/user
: Retrieve the authenticated user's information.POST /api/logout
: Log out the user by removing the JWT cookie.
You can check the complete documentation here: https://josehurtadobaeza.super.site/databases/blog-posts-database/doing-golang-jwt-authentication-tutorial-freecodecamp