Authentication & Authorization π
7 min read
Authentication & Authorization π
Welcome to the world of Authentication and Authorization in Gin! It might sound like a high-tech security firm, but by the end of this guide, you'll be the bouncer of your own application, deciding who gets in and what they're allowed to do.
Authentication is all about verifying who someone is. Think of it as checking an ID at the door. Authorization, on the other hand, is about what an authenticated person is allowed to do. Once they're inside, do they have access to the VIP lounge?
In the wild world of web applications, protecting your routes is crucial. You don't want just anyone to be able to access sensitive user data or perform administrative actions. That's the problem we're here to solve.
Getting Started
Before we dive in, make sure you have a Go environment set up and Gin installed. If not, a little birdie told me you can get started with these commands:
# Create a new project directory
mkdir gin-auth-guide
cd gin-auth-guide
# Initialize a Go module
go mod init gin-auth-guide
# Install Gin
go get -u github.com/gin-gonic/gin Implementing Basic Authentication Middleware
Let's start with the simplest form of authentication: Basic Authentication. It's like a secret knock to get into a clubhouse. While not the most secure method for production applications (passwords are sent in the headers, so HTTPS is a must!), it's a great starting point to understand the concept of middleware.
The Problem: You have an /admin route that should only be accessible to a select few with a username and password.
The Solution: Gin's built-in BasicAuth middleware. This middleware will check the Authorization header of incoming requests for a valid username and password before it ever reaches your handler.
Here's how you can set it up:
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// Group using the BasicAuth() middleware
authorized := router.Group("/admin", gin.BasicAuth(gin.Accounts{
"foo": "bar", // user:foo password:bar
"austin": "1234", // user:austin password:1234
}))
// /admin/secrets endpoint
authorized.GET("/secrets", func(c *gin.Context) {
// get user, it was set by the BasicAuth middleware
user := c.MustGet(gin.AuthUserKey).(string)
c.JSON(http.StatusOK, gin.H{"user": user, "secret": "The secret ingredient is love... and a little bit of Gin."})
})
router.Run(":8080")
}When a request comes to the /admin/secrets route, Gin's BasicAuth middleware jumps into action. If the authentication is successful, the next handler is called. Otherwise, a 401 Unauthorized status is returned.
Understanding JWT (JSON Web Tokens) Flow
Basic Auth is neat, but for modern, scalable applications, especially those with separate frontend and backend services (microservices), we need a more robust solution. Enter JSON Web Tokens, or JWTs (pronounced "jot").
The Problem: How do you securely transmit information between parties as a JSON object, in a way that is compact and self-contained? How can a server know a user is authenticated on subsequent requests without having to look up their session in a database every time?
The Solution: JWTs! A JWT is a token-based, stateless authentication mechanism. This means the server doesn't need to store session information.
Here's a simplified flow of how JWT authentication works:
- User Login: The user sends their credentials (like a username and password) to the server.
- Token Generation: The server validates the credentials. If they're correct, it generates a JWT and sends it back to the client.
- Token Storage: The client stores this token, often in local storage or a secure cookie.
- Subsequent Requests: For every subsequent request to a protected route, the client includes the JWT in the
Authorizationheader, usually as a "Bearer" token. - Token Verification: The server receives the request, plucks the JWT from the header, and verifies its signature to ensure it's authentic and hasn't been tampered with.
- Access Granted: If the token is valid, the server processes the request and sends back the desired resource.
Anatomy of a JWT: A JWT consists of three parts separated by dots (.):
- Header: Contains the token type (JWT) and the signing algorithm used (e.g., HS256).
- Payload: Contains the "claims," which are statements about an entity (typically, the user) and additional data. Some standard claims are
iss(issuer),exp(expiration time), andsub(subject). - Signature: To create the signature, you take the encoded header, the encoded payload, a secret, and sign that.
Fun Fact: The payload of a JWT is Base64Url encoded, not encrypted! This means anyone can decode it and see what's inside. Therefore, you should never store sensitive information in the payload.
Generating and Verifying JWTs in Gin Handlers
Now that we understand the theory, let's get our hands dirty and generate some JWTs. For this, we'll need a popular Go package for handling JWTs.
First, let's get the package:
go get -u github.com/golang-jwt/jwt/v5 Generating a JWT:
Let's create a /login endpoint. When a user successfully logs in, we'll generate a JWT for them.
package main
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
var jwtKey = []byte("my_secret_key")
type Claims struct {
Username string `json:"username"`
jwt.RegisteredClaims
}
func login(c *gin.Context) {
var creds struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := c.ShouldBindJSON(&creds); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
return
}
// In a real application, you'd check the username and password against a database
if creds.Username != "myuser" || creds.Password != "mypassword" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
expirationTime := time.Now().Add(5 * time.Minute)
claims := &Claims{
Username: creds.Username,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(expirationTime),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not generate token"})
return
}
c.JSON(http.StatusOK, gin.H{"token": tokenString})
}
func main() {
router := gin.Default()
router.POST("/login", login)
router.Run(":8080")
}In this example, after a successful login, we create a set of claims including the username and an expiration time. We then create a new token with these claims and sign it with our secret key.
Protecting Private Routes with Custom Auth Middleware
Now for the grand finale: creating our own middleware to protect our private routes. This middleware will intercept incoming requests, check for a valid JWT, and either grant access or send them packing.
The Problem: You have a /profile route that should only be accessible to logged-in users with a valid JWT.
The Solution: A custom authentication middleware.
Here's how you can create and use this middleware:
package main
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
var jwtKey = []byte("my_secret_key")
type Claims struct {
Username string `json:"username"`
jwt.RegisteredClaims
}
func authMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
c.Abort()
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Bearer token required"})
c.Abort()
return
}
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token signature"})
c.Abort()
return
}
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid token"})
c.Abort()
return
}
if !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
c.Abort()
return
}
c.Set("username", claims.Username)
c.Next()
}
}
func login(c *gin.Context) {
// ... (same login handler as before)
}
func profile(c *gin.Context) {
username, _ := c.Get("username")
c.JSON(http.StatusOK, gin.H{"message": "Welcome to your profile!", "user": username})
}
func main() {
router := gin.Default()
router.POST("/login", login)
protected := router.Group("/api")
protected.Use(authMiddleware())
{
protected.GET("/profile", profile)
}
router.Run(":8080")
}In our authMiddleware, we first extract the token from the Authorization header. We then parse and validate the token. If everything checks out, we set the username in the context so that it can be accessed by the next handler and call c.Next() to pass the request along. If the token is invalid or missing, we abort the request with an unauthorized error.
By creating a route group and applying the middleware to it, we can easily protect multiple routes with the same authentication logic.
And there you have it! You've successfully implemented both basic and JWT-based authentication in your Gin application. You're now equipped to secure your APIs and build robust, real-world applications.
Further Reading
- Gin Web Framework Documentation: https://gin-gonic.com/docs/
- Go JWT Package Documentation: https://pkg.go.dev/github.com/golang-jwt/jwt/v5
- JWT Introduction: https://jwt.io/introduction
Challenge
You are tasked with securing a Gin web application using JSON Web Tokens (JWT). Your goal is to implement a middleware function named AuthMiddleware that intercepts incoming requests to protected routes.
This middleware must perform the following actions:
- Retrieve the
Authorizationheader from the request. - Validate that the header value is formatted as a "Bearer" token (e.g.,
Bearer <token>). If not, or if the header is missing, it should abort the request with an HTTP status of401 Unauthorizedand a JSON response{"error": "Authorization header required"}. - Parse the extracted token string. The token is signed using the HS256 algorithm and a predefined secret key, which is provided in the initial code as
jwtKey. - During parsing, validate the token's signature and claims. Specifically, ensure it's not expired.
- If the token is invalid for any reason (bad signature, expired, malformed), abort the request with an HTTP status of
401 Unauthorizedand a JSON response{"error": "Invalid token"}. - If the token is valid, extract the
usernameclaim from the token's payload. - Store the extracted
usernamein thegin.Contextwith the key"username". - Call
c.Next()to pass control to the next handler in the chain.
Complete the AuthMiddleware function in the provided code to fulfill these requirements.
Expected result
The completed AuthMiddleware function should correctly parse and validate a JWT from the Authorization header. It should handle missing or malformed tokens, validate the token's signature and expiration, and pass the username claim to subsequent handlers via the Gin context upon success.
Here is a correct implementation:
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
c.Abort()
return
}
// The token should be in the format "Bearer <token>"
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || parts[0] != "Bearer" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header format must be Bearer {token}"})
c.Abort()
return
}
tokenString := parts[1]
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
c.Abort()
return
}
// This handles expired tokens as well
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
c.Abort()
return
}
if !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
c.Abort()
return
}
// Set the user information in the context for downstream handlers
c.Set("username", claims.Username)
c.Next()
}
}