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/rbac-hierarchy-and-tenant.md
View on GitHub# RBAC — Role Hierarchy & Multi-Tenant Authorization
See also: `rbac-middleware.md`, `rbac-resource-and-impersonation.md`
## Role Hierarchy
Encode hierarchy as a map — higher-ranked roles inherit lower-ranked permissions.
```go
// internal/auth/roles.go
package auth
var roleRank = map[string]int{
"guest": 0,
"user": 1,
"moderator": 2,
"admin": 3,
"superadmin": 4,
}
// HasRoleAtLeast returns true if userRole has rank >= requiredRole.
// Unknown roles are denied — never defaulted to guest.
func HasRoleAtLeast(userRole, requiredRole string) bool {
ur, ok1 := roleRank[userRole]
rr, ok2 := roleRank[requiredRole]
return ok1 && ok2 && ur >= rr
}
```
```go
// pkg/middleware/rbac.go
// RequireMinRole allows any role with rank >= minRole.
func RequireMinRole(minRole string) gin.HandlerFunc {
return func(c *gin.Context) {
claims := claimsFromContext(c)
if claims == nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
if !auth.HasRoleAtLeast(claims.Role, minRole) {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "insufficient privileges"})
return
}
c.Next()
}
}
```
---
## Multi-Tenant Authorization
In multi-tenant systems, users belong to a tenant. Requests must be validated for both authentication AND tenant membership.
**Add TenantID to claims:**
```go
type Claims struct {
jwt.RegisteredClaims
UserID string `json:"uid"`
Email string `json:"email"`
Role string `json:"role"`
TenantID string `json:"tid"`
}
```
**Tenant middleware:**
```go
// pkg/middleware/tenant.go
const TenantIDKey = "tenant_id"
func RequireTenant() gin.HandlerFunc {
return func(c *gin.Context) {
claims := claimsFromContext(c)
if claims == nil || claims.TenantID == "" {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "tenant context required"})
return
}
c.Set(TenantIDKey, claims.TenantID)
c.Next()
}
}
```
**Enforce tenant isolation in repositories — always scope queries to the tenant:**
```go
func (r *gormPostRepository) GetByID(ctx context.Context, tenantID, postID string) (*domain.Post, error) {
var m PostModel
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND id = ?", tenantID, postID).
First(&m).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, domain.ErrNotFound
}
return nil, domain.ErrInternal
}
return m.ToDomain(), nil
}
```
**Handler reads tenant from context:**
```go
func (h *PostHandler) GetByID(c *gin.Context) {
tenantID := c.GetString(middleware.TenantIDKey)
type uriParams struct {
ID string `uri:"id" binding:"required"`
}
var params uriParams
if err := c.ShouldBindURI(¶ms); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
return
}
post, err := h.svc.GetByID(c.Request.Context(), tenantID, params.ID)
if err != nil {
handleServiceError(c, err, h.logger)
return
}
c.JSON(http.StatusOK, post)
}
```
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: 323k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 323k | 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: 323k | 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: 323k | Updated | Claude CodeCodex | Verified | Install |