A robust REST API authentication system built with Go, Gin framework, MongoDB, and JWT tokens. This project provides user registration, login, and role-based access control (RBAC) features.
- β User Registration & Login
- β JWT Authentication (Access & Refresh Tokens)
- β Password Hashing with bcrypt
- β Role-Based Access Control (ADMIN/USER)
- β MongoDB Integration
- β Input Validation
- β Protected Routes with Middleware
Before running this project, make sure you have the following installed:
git clone https://github.com/Tanathorn-Rin/go-authentication-system.git
cd go-authentication-systemgo mod downloaddocker run -d -p 27017:27017 --name mongodb-auth mongo:latestbrew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community- Create a free account at MongoDB Atlas
- Create a cluster and get your connection string
- Update the connection string in
config/database.go
go run main.goThe server will start on http://localhost:8080
POST /signup
Content-Type: application/json
{
"first_name": "John",
"last_name": "Doe",
"email": "[email protected]",
"password": "securepassword123",
"phone": "1234567890",
"role": "USER"
}Response:
{
"message": "User created successfully"
}POST /login
Content-Type: application/json
{
"email": "[email protected]",
"password": "securepassword123"
}Response:
{
"user": { ... },
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}GET /users
Authorization: Bearer <your_jwt_token>Response:
[
{
"user_id": "...",
"first_name": "John",
"last_name": "Doe",
"email": "[email protected]",
"role": "USER",
...
}
]GET /users/:id
Authorization: Bearer <your_jwt_token>Note: Regular users can only access their own profile. ADMIN can access any user profile.
Response:
{
"user_id": "...",
"first_name": "John",
"last_name": "Doe",
"email": "[email protected]",
"role": "USER",
...
}This API uses JWT (JSON Web Tokens) for authentication. After logging in, include the token in the Authorization header:
Authorization: Bearer <your_jwt_token>
- Access Token: 24 hours
- Refresh Token: 7 days
Authentication-system/
βββ config/
β βββ auth-key.go # JWT key generation
β βββ database.go # MongoDB connection
βββ controllers/
β βββ userControllers.go # User-related handlers
βββ helpers/
β βββ token.go # JWT & password utilities
βββ middleware/
β βββ auth.go # JWT authentication middleware
βββ models/
β βββ user.go # User model/schema
βββ routes/
β βββ routes.go # Route definitions
βββ main.go # Application entry point
βββ go.mod # Go module dependencies
βββ go.sum # Dependency checksums
Update MongoDB connection string in config/database.go:
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")The default database name is usersdb. Change it in config/database.go if needed:
return Client.Database("usersdb").Collection(collectionName)The server runs on port 8080 by default. Change it in main.go:
port := "8080"- gin-gonic/gin - HTTP web framework
- go-playground/validator - Input validation
- golang-jwt/jwt - JWT implementation
- mongo-driver - MongoDB driver
- bcrypt - Password hashing
Signup:
curl -X POST http://localhost:8080/signup \
-H "Content-Type: application/json" \
-d '{
"first_name": "Jane",
"last_name": "Smith",
"email": "[email protected]",
"password": "password123",
"phone": "9876543210",
"role": "USER"
}'Login:
curl -X POST http://localhost:8080/login \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "password123"
}'Get Users (with token):
curl -X GET http://localhost:8080/users \
-H "Authorization: Bearer YOUR_TOKEN_HERE"- Import the endpoints listed above
- For protected routes, add the token in the Authorization tab:
- Type: Bearer Token
- Token: Paste your JWT token
- Password Hashing: Passwords are hashed using bcrypt before storage
- JWT Tokens: Secure token-based authentication
- Role-Based Access Control: Different permissions for ADMIN and USER roles
- Input Validation: All inputs are validated before processing
- Secure Headers: Authorization headers for protected routes
server selection error: server selection timeout
Solution: Make sure MongoDB is running:
# If using Docker
docker start mongodb-auth
# If using Homebrew
brew services start mongodb-communitybind: address already in use
Solution: Change the port in main.go or kill the process using port 8080:
lsof -ti:8080 | xargs kill -9no required module provides package
Solution: Run:
go mod tidy
go mod downloadThis project is open source and available under the MIT License.
Tanathorn Rin
- GitHub: @Tanathorn-Rin
Contributions, issues, and feature requests are welcome! Feel free to check the issues page.
Give a βοΈ if this project helped you!
Note: This is a learning project. For production use, consider adding:
- Environment variables for sensitive data
- HTTPS/TLS support
- Rate limiting
- Email verification
- Password reset functionality
- Refresh token rotation
- Better error handling
- Unit tests
- API documentation (Swagger/OpenAPI)