This project demonstrates a basic user authentication and authorization system using Go Fiber and JWT (JSON Web Token). Users can log in with a username and password to receive a JWT token, which can be used to access protected routes.
- User login and JWT token generation
- Protected route that requires a valid JWT token
- Basic username and password authentication
├── main.go
├── go.mod
├── go.sum
├── handler
│ ├── auth.go
├── middleware
│ ├── jwt.go
└── README.md
- Go (1.16 or higher)
- Git
-
Clone the repository:
git clone https://github.com/aselasperera/Go-Fiber-JWT-Auth cd your-repo-name -
Install dependencies:
go mod tidy
-
Run the application:
go run main.go
The server will start on localhost:4000.
-
URL:
/login -
Method:
POST -
Headers:
Content-Type: application/json -
Body:
{ "username": "Chek", "password": "123456" } -
Success Response:
- Code: 200 OK
- Content: JWT token string
-
Error Response:
- Code: 401 Unauthorized
- Content:
Invalid credentials
-
URL:
/protected -
Method:
GET -
Headers:
Authorization: Bearer <your-jwt-token> -
Success Response:
- Code: 200 OK
- Content:
Welcome to the protected area
-
Error Response:
- Code: 401 Unauthorized
- Content:
Missing authorization headerorInvalid token
-
Login Request:
-
URL:
http://localhost:4000/login -
Method:
POST -
Body:
{ "username": "Chek", "password": "123456" }
-
-
Protected Request:
- URL:
http://localhost:4000/protected - Method:
GET - Headers:
Authorization: Bearer <your-jwt-token>
- URL:
-
Login Request:
curl -X POST http://localhost:4000/login -H "Content-Type: application/json" -d '{"username": "Chek", "password": "123456"}'
This will return a JWT token if the credentials are correct.
-
Protected Request:
Replace
<your-jwt-token>with the token received from the login request:curl -X GET http://localhost:4000/protected -H "Authorization: Bearer <your-jwt-token>"If the token is valid, you should receive the message "Welcome to the protected area".
This project is licensed under the MIT License - see the LICENSE file for details.
- Fiber - Express inspired web framework written in Go
- golang-jwt - A Go implementation of JSON Web Tokens