Skip to content

Instantly share code, notes, and snippets.

@dipeshhkc
Last active May 22, 2021 10:32
Show Gist options
  • Save dipeshhkc/7e3e5c62974b25421f6410e7c4181d7b to your computer and use it in GitHub Desktop.
Save dipeshhkc/7e3e5c62974b25421f6410e7c4181d7b to your computer and use it in GitHub Desktop.
package middleware
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 := handler.ValidateToken(tokenString); err != nil {
fmt.Println("token", tokenString, err.Error())
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"])
fmt.Println("during authorization", 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