Created
May 4, 2019 18:54
-
-
Save linux08/1c6f98f92a94d862ab12a56a4359c5a1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
func JwtVerify(next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
var header = r.Header.Get("x-access-token") //Grab the token from the header | |
header = strings.TrimSpace(header) | |
if header == "" { | |
//Token is missing, returns with error code 403 Unauthorized | |
w.WriteHeader(http.StatusForbidden) | |
json.NewEncoder(w).Encode(Exception{Message: "Missing auth token"}) | |
return | |
} | |
tk := &models.Token{} | |
_, err := jwt.ParseWithClaims(header, tk, func(token *jwt.Token) (interface{}, error) { | |
return []byte("secret"), nil | |
}) | |
if err != nil { | |
w.WriteHeader(http.StatusForbidden) | |
json.NewEncoder(w).Encode(Exception{Message: err.Error()}) | |
return | |
} | |
ctx := context.WithValue(r.Context(), "user", tk) | |
next.ServeHTTP(w, r.WithContext(ctx)) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment