A RESTful authentication API built with Go, Gin, MongoDB, and JWT. The project uses a layered structure for routing, HTTP controllers, business logic, persistence, and shared utilities.
- User registration with input validation and bcrypt password hashing
- Login with short-lived access tokens and refresh tokens
- JWT authentication through HTTP-only cookies
- Protected profile and logout endpoints
- MongoDB persistence
- Rate limiting for profile requests
- Input normalization for user names and email addresses
- Go 1.25.1 or later
- MongoDB running locally or remotely
- A MongoDB connection string
Create a .env file in the project root:
MONGO_URI=mongodb://localhost:27017
ACCESS_SECRET=replace-with-a-long-random-access-secret
REFRESH_SECRET=replace-with-a-long-random-refresh-secretThe application stores data in the authDB database. Keep the access and refresh secrets private and use different values for each.
Install dependencies and start the API:
go mod download
go run .The server listens on http://localhost:8080.
Build and test the project with:
go build ./...
go test ./...Base URL: http://localhost:8080
| Method | Endpoint | Authentication | Description |
|---|---|---|---|
| GET | / |
None | Health check |
| POST | /user/register |
None | Register a user |
| POST | /user/login |
None | Log in and set JWT cookies |
| POST | /user/refresh |
None | Refresh the access token |
| POST | /user/logout |
Access token | Clear authentication cookies |
| GET | /user/profile |
Access token | Return the current user's profile |
curl -X POST http://localhost:8080/user/register \
-H "Content-Type: application/json" \
-d '{"name":"John Doe","email":"john@example.com","password":"Secret@123"}'curl -i -c cookies.txt -X POST http://localhost:8080/user/login \
-H "Content-Type: application/json" \
-d '{"email":"john@example.com","password":"Secret@123"}'Save the response cookies when using a command-line client. Send them with protected requests:
curl -b cookies.txt http://localhost:8080/user/profileAccess tokens expire after 15 minutes. Refresh tokens expire after 7 days. The browser must be configured to retain and send cookies for protected requests.
.
├── main.go
├── config/ # Environment loading and MongoDB connection
├── controller/ # HTTP request handlers
├── middleware/ # Authentication and rate limiting
├── model/ # Data models
├── repository/ # MongoDB operations
├── routes/ # API route registration
├── services/ # Application and authentication logic
└── utils/ # JWT, hashing, validation, and sanitization helpers
The request flow is:
Route -> Middleware -> Controller -> Service -> Repository -> MongoDB
- Passwords are stored as bcrypt hashes, never as plain text.
- JWT secrets must be supplied through environment variables and should be long, random values.
- Use HTTPS in deployed environments so authentication cookies cannot be exposed in transit.