auth

package
v1.13.2 Latest Latest
Warning

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

Go to latest
Published: May 18, 2025 License: MIT Imports: 6 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
}

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 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.

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