forked from nzoschke/gofaas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
60 lines (51 loc) · 1.48 KB
/
jwt.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package gofaas
import (
"encoding/base64"
"fmt"
"os"
"strings"
"github.com/aws/aws-lambda-go/events"
jwt "github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
)
// JWTClaims validates the token in the Authorization header
// It returns a response with standard headers and claims if valid
// And an error response and an error if invalid
func JWTClaims(e events.APIGatewayProxyRequest, claims jwt.Claims) (events.APIGatewayProxyResponse, jwt.Claims, error) {
r := events.APIGatewayProxyResponse{
Headers: map[string]string{
"Access-Control-Allow-Origin": header(e, "Origin"),
},
StatusCode: 200,
}
// for convenience, "pass" auth if no hash key is set
k := os.Getenv("AUTH_HASH_KEY")
if k == "" {
return r, claims, nil
}
key, err := base64.StdEncoding.DecodeString(k)
if err != nil {
r.Body = fmt.Sprintf("{\"error\": %q}", err)
r.StatusCode = 500
return r, claims, errors.WithStack(err)
}
tokenString := strings.TrimPrefix(header(e, "Authorization"), "Bearer ")
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return key, nil
})
if token != nil && !token.Valid {
err = errors.New("Invalid token")
}
if err != nil {
r.Body = fmt.Sprintf("{\"error\": %q}", err)
r.StatusCode = 401
return r, claims, errors.WithStack(err)
}
return r, claims, nil
}
func header(e events.APIGatewayProxyRequest, name string) string {
if v := e.Headers[name]; v != "" {
return v
}
return e.Headers[strings.ToLower(name)]
}