Skip to content

Instantly share code, notes, and snippets.

@renta
Last active May 19, 2021 20:53
Show Gist options
  • Save renta/e6c3a67f40a3a8edd251c8c804293c7e to your computer and use it in GitHub Desktop.
Save renta/e6c3a67f40a3a8edd251c8c804293c7e to your computer and use it in GitHub Desktop.
Gin framework JWT token extractor middleware
package gin
import (
"crypto/rsa"
"net/http"
"github.com/gin-gonic/gin"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwt"
)
// JWTTokenParser extract JWT token form header Authorization and validate it with a RS256 public key
// example of usage: h.GET("/test/:id", JWTTokenParser(publicKey), someHandler.getTest)
func JWTTokenParser(publicKey *rsa.PublicKey) gin.HandlerFunc {
return func(c *gin.Context) {
token, err := jwt.ParseHeader(
c.Request.Header,
"Authorization",
jwt.WithValidate(true),
jwt.WithVerify(jwa.RS256, publicKey),
)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
return
}
c.Set("jwtToken", token)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment