This project demonstrates how to build a secure authentication system in a Golang application. It includes examples of login, registration, and forgot password functionalities, as well as implementing access and refresh tokens. The project uses MongoDB for data storage, Redis for caching and session management, and follows clean architecture principles.
- Secure authentication system
- Login and registration endpoints
- Forgot password functionality
- Access and refresh tokens
- Middleware for JWT authentication
- Example endpoints for protected routes
- MongoDB for data storage
- Redis for caching and session management
- Clean architecture
- Go 1.16 or higher
- A basic understanding of JWTs
- MongoDB
- Redis
-
Clone the repository:
git clone https://github.com/rohankarn35/golang-jwt.git cd golang-jwt
-
Install dependencies:
go mod tidy
-
Create a
.env
file with the following fields:REDIS_ADDR=<redis address> REDIS_PASSWORD= # Leave empty if Redis has no password REDIS_DB=0 # Redis database number (default is 0) MONGODB_URI=mongodb+srv://<name>:<password>@cluster0.a4ecxsw.mongodb.net/?retryWrites=true&w=majority&appName=<clustername> JWTSECRET= your-secret-key
-
Run the application:
go run main.go
-
Use a tool like Postman to test the endpoints.
POST /login
: Authenticate a user and receive a JWT.POST /register
: Register a new user.POST /forgot-password
: Initiate password reset process.POST /auth/logout
: Logout a user.POST /auth/reset-password
: Reset a user's password.POST /auth/refresh
: Generate a new refresh token.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": "user_id",
"exp": time.Now().Add(time.Hour * 72).Unix(),
})
tokenString, err := token.SignedString([]byte("your-256-bit-secret"))
if err != nil {
log.Fatal(err)
}
fmt.Println(tokenString)
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte("your-256-bit-secret"), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
fmt.Println(claims["user_id"])
} else {
fmt.Println(err)
}
This project is licensed under the MIT License. See the LICENSE file for details.
Contributions are welcome! Please open an issue or submit a pull request.
- jwt-go library for JWT implementation in Go.
- Redis for caching and session management.
- Gin for the HTTP web framework.
- Go Modules for dependency management.