From fad6b6536a3c31c0945668283a047c370fa30212 Mon Sep 17 00:00:00 2001 From: Matthieu Lamalle Date: Thu, 25 Jul 2019 14:29:28 +0200 Subject: [PATCH] add jwt auth for future use --- security/security.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 security/security.go diff --git a/security/security.go b/security/security.go new file mode 100644 index 0000000..59a348c --- /dev/null +++ b/security/security.go @@ -0,0 +1,34 @@ +package security + +import ( + "cadoles/graphql/config" + "fmt" + "log" + "net/http" + + jwt "github.com/dgrijalva/jwt-go" +) + +// Handle security middleware aims to implement a JWT authentication. +func Handle(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + tokenString := r.Header.Get("Authorization")[7:] // 7 corresponds to "Bearer " + + token, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) + } + conf := config.GetConfig() + + var secret = conf.JWT_SECRET // Prefer to store this secret in a configuration file + + return []byte(secret), nil + }) + + if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { + log.Printf("JWT Authenticated OK (app: %s)", claims["app"]) + + next.ServeHTTP(w, r) + } + }) +}