henriqueatila/golang-gin-best-practices / skills/golang-gin-auth
golang-gin-auth
VerifiedJWT auth and RBAC for Go Gin APIs. Use when adding login, signup, JWT tokens, role checks, protected routes, or password hashing to a Gin app.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 7.4 KB |
| metadata.json | config | 499 B |
| references/auth-implementation-core.md | markdown | 3.5 KB |
| references/auth-implementation-handlers.md | markdown | 3.9 KB |
| references/auth-ip-rate-limiter.md | markdown | 1.5 KB |
| references/auth-middleware.md | markdown | 2.2 KB |
| references/captcha-middleware.md | markdown | 3.8 KB |
| references/jwt-patterns-blacklist.md | markdown | 3.4 KB |
| references/jwt-patterns-rs256.md | markdown | 2.7 KB |
| references/jwt-patterns-storage-and-csrf.md | markdown | 3.8 KB |
| references/jwt-patterns-tokens.md | markdown | 4.8 KB |
| references/oauth2-flows.md | markdown | 3.8 KB |
| references/oauth2-github-profile.md | markdown | 1.3 KB |
| references/oauth2-google-and-security.md | markdown | 2.0 KB |
| references/rbac-hierarchy-and-tenant.md | markdown | 3.2 KB |
| references/rbac-middleware.md | markdown | 4.2 KB |
| references/rbac-resource-and-impersonation.md | markdown | 3.8 KB |
| references/rbac-route-wiring.md | markdown | 1.6 KB |
references/jwt-patterns-blacklist.md
View on GitHub# JWT Patterns — Token Blacklisting (Redis)
See also: `jwt-patterns-tokens.md`, `jwt-patterns-storage-and-csrf.md`, `jwt-patterns-rs256.md`
## Token Blacklisting (Redis)
Tokens are stateless — you can't "delete" one. Blacklisting stores revoked token IDs in Redis with TTL matching the token's remaining lifetime. On every request, middleware checks Redis before accepting the token.
```go
// internal/auth/blacklist.go
package auth
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
type Blacklist struct {
rdb *redis.Client
prefix string
}
func NewBlacklist(rdb *redis.Client) *Blacklist {
return &Blacklist{rdb: rdb, prefix: "jwt:revoked:"}
}
// Revoke adds a token ID to the blacklist until its expiry.
func (b *Blacklist) Revoke(ctx context.Context, tokenID string, expiry time.Time) error {
ttl := time.Until(expiry)
if ttl <= 0 {
return nil // already expired — no need to blacklist
}
key := b.prefix + tokenID
if err := b.rdb.Set(ctx, key, "1", ttl).Err(); err != nil {
return fmt.Errorf("blacklist.Revoke: %w", err)
}
return nil
}
// IsRevoked returns true if the token ID has been revoked.
func (b *Blacklist) IsRevoked(ctx context.Context, tokenID string) (bool, error) {
key := b.prefix + tokenID
val, err := b.rdb.Exists(ctx, key).Result()
if err != nil {
return false, fmt.Errorf("blacklist.IsRevoked: %w", err)
}
return val > 0, nil
}
```
**Middleware integration:** After `ParseAccessToken`, check `blacklist.IsRevoked(ctx, claims.ID)` before calling `c.Next()`. The `claims.ID` maps to the `jti` field in `RegisteredClaims`.
**Logout endpoint:**
```go
func (h *AuthHandler) Logout(c *gin.Context) {
val, exists := c.Get(middleware.ClaimsKey)
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
claims, ok := val.(*auth.Claims)
if !ok {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal server error"})
return
}
expiry := claims.ExpiresAt.Time
if err := h.blacklist.Revoke(c.Request.Context(), claims.ID, expiry); err != nil {
h.logger.Error("failed to revoke token", "error", err, "jti", claims.ID)
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal server error"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "logged out"})
}
```
## Complete Auth Flow Wiring
```go
// cmd/api/main.go — protected routes with blacklist check
protected := api.Group("")
protected.Use(middleware.Auth(tokenCfg, logger))
{
protected.POST("/auth/logout", authHandler.Logout)
protected.GET("/users/me", userHandler.GetMe)
protected.GET("/users/:id", userHandler.GetByID)
admin := protected.Group("/admin")
admin.Use(middleware.RequireRole("admin"))
{
admin.GET("/users", userHandler.List)
admin.DELETE("/users/:id", userHandler.Delete)
}
}
```
**Sequence for a protected request:**
1. Client sends `Authorization: Bearer <access_token>`
2. `Auth` middleware extracts and validates the token
3. Middleware checks `blacklist.IsRevoked(ctx, claims.ID)` → 401 if revoked
4. Claims injected via `c.Set(ClaimsKey, claims)` and `c.Set(UserIDKey, claims.UserID)`
5. Handler calls `c.GetString(UserIDKey)` or `c.Get(ClaimsKey)` to read identity
6. Handler passes `c.Request.Context()` to all downstream calls
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |