Created
April 15, 2020 12:37
-
-
Save agzuniverse/5cb537f437c0ebd93c6dfc6ece88cc58 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
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"net/http" | |
"strings" | |
"github.com/dgrijalva/jwt-go" | |
) | |
func middleware(next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
authHeader := strings.Split(r.Header.Get("Authorization"), "Bearer ") | |
if len(authHeader) != 2 { | |
fmt.Println("Malformed token") | |
w.WriteHeader(http.StatusUnauthorized) | |
w.Write([]byte("Malformed Token")) | |
} else { | |
jwtToken := authHeader[1] | |
token, err := jwt.Parse(jwtToken, func(token *jwt.Token) (interface{}, error) { | |
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { | |
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) | |
} | |
return []byte(SECRETKEY), nil | |
}) | |
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { | |
ctx := context.WithValue(r.Context(), "props", claims) | |
// Access context values in handlers like this | |
// props, _ := r.Context().Value("props").(jwt.MapClaims) | |
next.ServeHTTP(w, r.WithContext(ctx)) | |
} else { | |
fmt.Println(err) | |
w.WriteHeader(http.StatusUnauthorized) | |
w.Write([]byte("Unauthorized")) | |
} | |
} | |
}) | |
} | |
func pong(w http.ResponseWriter, r *http.Request) { | |
w.WriteHeader(http.StatusOK) | |
w.Write([]byte("pong")) | |
} | |
func main() { | |
http.Handle("/ping", middleware(http.HandlerFunc(pong))) | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment