Last active
May 19, 2021 20:53
-
-
Save renta/e6c3a67f40a3a8edd251c8c804293c7e to your computer and use it in GitHub Desktop.
Gin framework JWT token extractor middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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