A small, opinionated Go authentication example using Gin, JWT and MongoDB. It demonstrates a minimal signup/login flow, JWT generation + refresh token, middleware-protected endpoints, and a simple MongoDB-backed user model.
✅ Features
- User signup with validation
- User login with password verification and JWT access & refresh tokens
- Middleware that validates JWT and protects routes
- MongoDB for persistence
📁 Project layout (important files)
main.go– server bootstrap and route registrationroutes/authRouter.go– public routes (signup, login)routes/userRouter.go– user management (protected)controller/userController.go– handlers for signup, login, fetch usershelpers/tokenHelper.go– JWT helpers (generate/validate/update tokens)database/databaseConnection.go– MongoDB connection; uses.envmodels/userModel.go– user schema & validation rules
Requirements
- Go 1.25+ (see
go.mod) - A running MongoDB server or connection URI
Environment variables (.env)
Create a .env file in the project root with at least these values:
MONGODB_URL=mongodb://localhost:27017
PORT=8000
SECRET_KEY=<a-strong-random-secret>
Quick start
- Clone the repository:
git clone <your-repo-url> golang-jwt-project
cd golang-jwt-project-
Create
.env(see above) -
Install dependencies and tidy modules:
go mod tidy- Run the server locally:
go run main.goThe server runs on the port configured by PORT (defaults to 8000).
API routes & examples
-
POST /users/signup
- Payload (example):
{ "first_name": "Stephan", "last_name": "Mut", "email": "stephan@gmail.com", "password": "qwert1234", "phone": "1234567890", "user_type": "USER" } - Response: 200 (created user insertion result) or 400/500 errors with messages.
- Payload (example):
-
POST /users/login
- Payload:
{ "email": "stephan@gmail.com", "password": "qwert1234" } - Successful response: user object including
tokenandrefresh_token. - Common errors:
{"error":"email or password is incorrect"}when email or password mismatch.
- Payload:
-
GET /users (protected)
-
GET /users/:user_id (protected)
- These endpoints require an authorization token in the request header named
token(the middleware readsc.Request.Header.Get("token")).
- These endpoints require an authorization token in the request header named
How the auth flow works (brief)
- Signup: validates the payload, hashes the password, saves user to MongoDB, generates access and refresh JWTs.
- Login: verifies user & password, issues tokens and updates token fields in DB.
- Middleware: the
Authenticatemiddleware inspects thetokenheader and validates the JWT usingSECRET_KEY.
Troubleshooting tips
- "no required module provides package "golang-jwt-project/controller"":
Make sure the module path in
go.modmatches your import paths. If you plan to publish the repo, consider using a full repo path (eg:module github.com/<user>/GO-Authentication) and update imports. {"error":"error occured"}from the middleware: this happens when notokenheader is sent;/users/loginand/users/signupmust be public routes (not behind the middleware) so POST login/signup must be called without a token.- If
go listcomplains about missing packages (eggo.mongodb.org/mongo-driver), rungo mod tidyorgo getto install dependencies.
Next steps / suggestions
- Use a proper repo module path in
go.mod(e.g.,github.com/<username>/GO-Authentication) to make imports predictable for others. - Add tests for controllers and middleware.
- Add a refresh token endpoint and token rotation logic for production-grade security.
If you want, I can:
- Update
go.modto a repository path and rewrite imports for you. - Add Postman collection / cURL examples for all endpoints.
Made with ❤️ — reach out if you want me to expand this README with deploy instructions, CI, or example Postman collection.