Skip to content

Instantly share code, notes, and snippets.

@dipeshhkc
Last active June 24, 2021 12:31
Show Gist options
  • Save dipeshhkc/1316b7670d13a35a4ce96fd3348d60c2 to your computer and use it in GitHub Desktop.
Save dipeshhkc/1316b7670d13a35a4ce96fd3348d60c2 to your computer and use it in GitHub Desktop.
//AuthorizeJWT -> to authorize JWT Token
func AuthorizeJWT() gin.HandlerFunc {
return func(ctx *gin.Context) {
const BearerSchema string = "Bearer "
authHeader := ctx.GetHeader("Authorization")
if authHeader == "" {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "No Authorization header found"})
}
tokenString := authHeader[len(BearerSchema):]
if token, err := utils.ValidateToken(tokenString); err != nil {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "Not Valid Token"})
} else {
if claims, ok := token.Claims.(jwt.MapClaims); !ok {
ctx.AbortWithStatus(http.StatusUnauthorized)
} else {
if token.Valid {
ctx.Set("userID", claims["userID"])
} else {
ctx.AbortWithStatus(http.StatusUnauthorized)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment