auth

package
v1.15.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 12, 2025 License: MIT Imports: 14 Imported by: 0

README

auth

auth middleware for gin framework.

Example of use

package main

import (
    "time"
    "github.com/gin-gonic/gin"
    "github.com/go-dev-frame/sponge/pkg/gin/middleware/auth"
    "github.com/go-dev-frame/sponge/pkg/gin/response"
)

func main() {
    r := gin.Default()

    // initialize jwt first
    auth.InitAuth([]byte("your-sign-key"), time.Hour*24) // default signing method is HS256
    // auth.InitAuth([]byte("your-sign-key"), time.Minute*24, WithInitAuthSigningMethod(HS512), WithInitAuthIssuer("foobar.com"))

    r.POST("/auth/login", Login)

    g := r.Group("/api/v1")
    g.Use(auth.Auth())
    //g.Use(auth.Auth(auth.WithExtraVerify(extraVerifyFn))) // add extra verify function

    g.GET("/user/:id", GetByID)
    //g.PUT("/user/:id", Create)
    //g.DELETE("/user/:id", DeleteByID)

    r.Run(":8080")
}

func Login(c *gin.Context) {
    // ......

    // Case 1: only uid for token
    {
        token, err := auth.GenerateToken("100")
    }

    // Case 2: uid and custom fields for token
    {
        uid := "100"
        fields := map[string]interface{}{
            "name":   "bob",
            "age":    10,
            "is_vip": true,
        }
        token, err := auth.GenerateToken(uid, auth.WithGenerateTokenFields(fields))
    }

    response.Success(c, token)
}

func GetByID(c *gin.Context) {
    uid := c.Param("id")

    // if necessary, claims can be got from gin context
    claims, ok := auth.GetClaims(c)
    //uid := claims.UID
    //name, _ := claims.GetString("name")
    //age, _ := claims.GetInt("age")
    //isVip, _ := claims.GetBool("is_vip")

    response.Success(c, gin.H{"id": uid})
}

func extraVerifyFn(claims *auth.Claims, c *gin.Context) error {
    // check if token is about to expire (less than 10 minutes remaining)
    if time.Now().Unix()-claims.ExpiresAt.Unix() < int64(time.Minute*10) {
        token, err := auth.RefreshToken(claims)
        if err != nil {
            return err
        }
        c.Header("X-Renewed-Token", token)
    }

    // judge whether the user is disabled, query whether jwt id exists from the blacklist
    //if CheckBlackList(uid, claims.ID) {
    //    return errors.New("user is disabled")
    //}

    return nil
}

Session Auth

package main

import (
  "github.com/gin-contrib/sessions"
  "github.com/gin-contrib/sessions/cookie"
  "github.com/gin-gonic/gin"
)

func main() {
  r := gin.Default()
  store := cookie.NewStore([]byte("secret"))
  r.Use(sessions.Sessions("mysession", store))

  r.GET("/incr", func(c *gin.Context) {
    session := sessions.Default(c)
    var count int
    v := session.Get("count")
    if v == nil {
      count = 0
    } else {
      count = v.(int)
      count++
    }
    session.Set("count", count)
    session.Save()
    c.JSON(200, gin.H{"count": count})
  })
  r.Run(":8000")
}

Redis Based
package main

import (
  "github.com/gin-contrib/sessions"
  "github.com/gin-contrib/sessions/redis"
  "github.com/gin-gonic/gin"
)

func main() {
  r := gin.Default()
  store, _ := redis.NewStore(10, "tcp", "localhost:6379", "", []byte("secret"))
  r.Use(sessions.Sessions("mysession", store))

  r.GET("/incr", func(c *gin.Context) {
    session := sessions.Default(c)
    var count int
    v := session.Get("count")
    if v == nil {
      count = 0
    } else {
      count = v.(int)
      count++
    }
    session.Set("count", count)
    session.Save()
    c.JSON(200, gin.H{"count": count})
  })
  r.Run(":8000")
}

Documentation

Overview

Package auth provides JWT authentication middleware for gin.

Index

Constants

View Source
const HeaderAuthorizationKey = "Authorization"

HeaderAuthorizationKey http header authorization key, value is "Bearer token"

Variables

View Source
var (
	HS256 = jwt.HS256
	HS384 = jwt.HS384
	HS512 = jwt.HS512
)

Functions

func Auth

func Auth(opts ...AuthOption) gin.HandlerFunc

Auth authorization middleware, support custom extra verify.

func DecodeSignedCookie added in v1.15.3

func DecodeSignedCookie(secretKeyBase string, decodedCookie string, cookieName string) (map[string]any, error)

DecodeSignedCookie decrypts a Rails 7.1+ encrypted cookie using the provided secretKeyBase and validates that its purpose matches the given cookieName. It returns the decoded session payload (the JSON contained in _rails.message).

The Rails encrypted cookie format is: base64(data)--base64(iv)--base64(authTag) Key derivation: PBKDF2-HMAC-SHA256(secret_key_base, "authenticated encrypted cookie", 1000, 32) Cipher: AES-256-GCM, AAD: empty

func GenerateToken

func GenerateToken(uid string, opts ...GenerateTokenOption) (string, error)

GenerateToken generates a jwt token with the given uid and options.

func GetClaims

func GetClaims(c *gin.Context) (*jwt.Claims, bool)

GetClaims get jwt claims from gin context.

func InitAuth

func InitAuth(signingKey []byte, expire time.Duration, opts ...InitAuthOption)

InitAuth initializes jwt options.

func ParseToken

func ParseToken(token string) (*jwt.Claims, error)

ParseToken parses the given token and returns the claims.

func RefreshToken

func RefreshToken(claims *jwt.Claims) (string, error)

RefreshToken create a new token with the given claims.

func UserIDFromSession added in v1.15.3

func UserIDFromSession(session map[string]any) (any, bool)

UserIDFromSession tries to extract the warden user id from a Rails session. It returns the id and true if found, otherwise (nil, false).

Types

type AuthOption

type AuthOption func(*authOptions)

AuthOption set the auth options.

func WithExtraVerify

func WithExtraVerify(fn ExtraVerifyFn) AuthOption

WithExtraVerify set extra verify function

func WithReturnErrReason

func WithReturnErrReason() AuthOption

WithReturnErrReason set return error reason

type Claims

type Claims = jwt.Claims

type ExtraVerifyFn

type ExtraVerifyFn = func(claims *jwt.Claims, c *gin.Context) error

ExtraVerifyFn extra verify function

type GenerateTokenOption

type GenerateTokenOption func(*generateTokenOptions)

GenerateTokenOption set the jwt options.

func WithGenerateTokenFields

func WithGenerateTokenFields(fields map[string]interface{}) GenerateTokenOption

WithGenerateTokenFields set custom fields value

type InitAuthOption

type InitAuthOption func(*initAuthOptions)

InitAuthOption set the jwt initAuthOptions.

func WithInitAuthIssuer

func WithInitAuthIssuer(issuer string) InitAuthOption

WithInitAuthIssuer set issuer value

func WithInitAuthSigningMethod

func WithInitAuthSigningMethod(sm *jwt.SigningMethodHMAC) InitAuthOption

WithInitAuthSigningMethod set signing method value

type SigningMethodHMAC

type SigningMethodHMAC = jwt.SigningMethodHMAC

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL