Categorygithub.com/flaviostutz/gin-jwt-parser
modulepackage
1.0.1
Repository: https://github.com/flaviostutz/gin-jwt-parser.git
Documentation: pkg.go.dev

# README

jwt-parse-middleware

Golang Gin middleware lib for parsing and checking JWT tokens in http requests

It parses and validates any incoming JWT token from requests and if a valid token is found, sets token claims to gin.Context attribute, accessible by ctx.Get("")

Check a full example at https://github.com/stutzlab/userme-demo-api/blob/master/api.go

Usage

  • Add module dependency
go get github.com/flaviostutz/gin-jwt-parser
  • Configure Gin routes
import (
    jwtparser "github.com/flaviostutz/gin-jwt-parser"
)

func NewHTTPServer() *HTTPServer {
    router := gin.Default()

    router.Use(jwtparser.Middleware(jwtparser.Config{
        RequiredIssuer:   "Berimbal",
        RequiredType:     "access",
        FromBearer:       "Authorization",
        JWTSigningMethod: "ES256",
        JWTVerifyKeyFile: "/my-public-key",
    }))
}
  • Check additional token data in specific API implementation
func listSomething() func(*gin.Context) {
    return func(c *gin.Context) {
      scope, _ := c.Get("scope")
      if scope != "admin" {
        return fmt.Errorf("User %s not authorized to access admin resource", sub)
      }

      sub, _ := c.Get("sub")
      logrus.Infof("User %s is listing items", sub)

      c.JSON(200, gin.H{})
      return
    }
}
  • In this example, only JWT tokens coming from HTTP Header "Authorization", with claim "iss==Berimbal", "typ==access" and whose signature was checked against "/my-public-key" are accepted.

  • After validating the JWT itself, if sets all claims as accessible properties from gin.Context

API

# Functions

Middleware Analyses http request, parse existing JWT tokens and set the claim map to gin.Context according to configuration.MiddlewareThe jwt token claims can be later checked by request handlers with "c.GetString(...)".

# Structs

Config configuration properties for JWT Parser.