Skip to content

Instantly share code, notes, and snippets.

@linux08
Created May 4, 2019 18:54
Show Gist options
  • Save linux08/1c6f98f92a94d862ab12a56a4359c5a1 to your computer and use it in GitHub Desktop.
Save linux08/1c6f98f92a94d862ab12a56a4359c5a1 to your computer and use it in GitHub Desktop.
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