A practical, modular example of JWT (JSON Web Token) authentication in Go, using the Gin web framework, GORM ORM, Bcrypt for password hashing, and JWT for secure authentication. This project is ideal for learning or as a starting point for your own secure Go APIs! 🔐
- Features
- Tech Stack
- Project Structure
- Getting Started
- Usage
- How JWT Authentication Works
- Example Middleware
- Environment Variables
- Dependencies
- Contributing
- License
- Acknowledgements
- User registration and login with JWT token generation
- Passwords securely hashed with Bcrypt
- Protected routes accessible only with valid JWT tokens
- Modular project structure (controllers, middleware, models)
- Environment-based configuration
Library | Purpose |
---|---|
Gin | Web framework & routing 🚦 |
GORM | ORM for database access 🗄️ |
Bcrypt | Password hashing 🔑 |
JWT | Token-based authentication 🪪 |
JWTAuth-using-Go/
├── controllers/ # Request handlers (auth logic)
├── initializers/ # App initialization (DB, env)
├── middleware/ # JWT authentication middleware
├── models/ # Data models (User struct, etc.)
├── main.go # Entry point
├── .env.example # Example environment variables
├── go.mod # Go module definition
├── go.sum # Go module checksums
- Go 1.18+ 🦫
- (Optional) Database, if you want persistent storage (I used Neon DB)
- Clone the repo
git clone https://github.com/ShashaankS/JWTAuth-using-Go.git
cd JWTAuth-using-Go
- Copy and edit environment variables
cp .env.example .env
- Install dependencies
go mod tidy
- Run the app
go run main.go
- Register:
POST /register
with user credentials - Login:
POST /login
with valid credentials to receive a JWT - Protected Routes: Include your JWT in the
Authorization: Bearer <token>
header to access secured endpoints
- User registers: Password is hashed with Bcrypt and stored securely in the database via GORM.
- User logs in: On successful login, the server issues a JWT containing user claims.
- Client stores JWT: Usually in localStorage or a cookie.
- Accessing protected routes: The client sends the JWT in the
Authorization
header. - Server validates JWT: Middleware checks the token before granting access.
Edit your .env
using .env.example
as a template:
SECRET
— Secret key for signing JWTs 🔑- Database connection strings (if needed)
- Inspired by community best practices for JWT in Go
- Uses patterns from the Go ecosystem
Note: This project is for educational use and may need enhancements for production (better error handling, token refresh, secure storage, etc.) 😎