-
Notifications
You must be signed in to change notification settings - Fork 0
/
security.go
34 lines (26 loc) · 939 Bytes
/
security.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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)
}
})
}