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/oauth2-flows.md
View on GitHub# OAuth2 / Social Login — Config, CSRF State & GitHub Flow
See also: `oauth2-google-and-security.md`
## Dependencies
```bash
go get golang.org/x/oauth2
go get golang.org/x/oauth2/github
go get golang.org/x/oauth2/google
```
## OAuth2 Config
Load all secrets from environment — never hardcode.
```go
// internal/auth/oauth2.go
package auth
import (
"os"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
"golang.org/x/oauth2/google"
)
func NewGitHubConfig() *oauth2.Config {
return &oauth2.Config{
ClientID: os.Getenv("GITHUB_CLIENT_ID"),
ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
RedirectURL: os.Getenv("GITHUB_REDIRECT_URL"),
Endpoint: github.Endpoint,
Scopes: []string{"user:email", "read:user"},
}
}
func NewGoogleConfig() *oauth2.Config {
return &oauth2.Config{
ClientID: os.Getenv("GOOGLE_CLIENT_ID"),
ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"),
RedirectURL: os.Getenv("GOOGLE_REDIRECT_URL"),
Endpoint: google.Endpoint,
Scopes: []string{"openid", "email", "profile"},
}
}
```
## CSRF State Management
Generate a random state token, store in Redis with short TTL, validate atomically on callback.
```go
// internal/auth/state.go
const stateTTL = 10 * time.Minute
func GenerateState() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
func StoreState(ctx context.Context, rdb *redis.Client, state string) error {
key := fmt.Sprintf("oauth2:state:%s", state)
return rdb.Set(ctx, key, "1", stateTTL).Err()
}
func ValidateAndDeleteState(ctx context.Context, rdb *redis.Client, state string) (bool, error) {
key := fmt.Sprintf("oauth2:state:%s", state)
n, err := rdb.Del(ctx, key).Result()
if err != nil {
return false, err
}
return n == 1, nil
}
```
## GitHub OAuth2 Flow
### Initiate Handler — `/auth/github`
```go
func (h *OAuth2Handler) GitHubLogin(c *gin.Context) {
state, err := auth.GenerateState()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
if err := auth.StoreState(c.Request.Context(), h.rdb, state); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
c.Redirect(http.StatusTemporaryRedirect, h.githubCfg.AuthCodeURL(state))
}
```
### Callback Handler — `/auth/github/callback`
```go
func (h *OAuth2Handler) GitHubCallback(c *gin.Context) {
ctx := c.Request.Context()
ok, err := auth.ValidateAndDeleteState(ctx, h.rdb, c.Query("state"))
if err != nil || !ok {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid state"})
return
}
token, err := h.githubCfg.Exchange(ctx, c.Query("code"))
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "authentication failed"})
return
}
profile, err := auth.FetchGitHubProfile(ctx, token.AccessToken)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
user, err := h.userService.FindOrCreateOAuth(ctx, "github", profile.ID, profile.Email, profile.Login)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
accessToken, refreshToken, err := h.tokenSvc.GeneratePair(user.ID, user.Email, user.Role)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
c.JSON(http.StatusOK, gin.H{"access_token": accessToken, "refresh_token": refreshToken})
}
```
See also: `oauth2-github-profile.md` for the `FetchGitHubProfile` helper.
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 |