forked from asabi/hello_go_lambda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhello_lambda.go
71 lines (60 loc) · 1.92 KB
/
hello_lambda.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
61
62
63
64
65
66
67
68
69
70
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/tidwall/gjson"
"time"
"github.com/dgrijalva/jwt-go"
)
func main() {
lambda.Start(Handler)
}
func Handler(ctx context.Context, evt json.RawMessage) (events.APIGatewayProxyResponse, error) {
signingKey := os.Getenv("SECRET")
passedToken := gjson.Get(string(evt), "jwt").String()
secret := gjson.Get(string(evt), "token")
returnVal := events.APIGatewayProxyResponse{
Body: "",
StatusCode: 200,
}
if secret.String() != os.Getenv("SECRET") {
createdToken, err := ExampleNew([]byte(signingKey))
if err == nil {
returnVal.Body = "bad token, here is a working jwt: " + createdToken
returnVal.StatusCode = 401
} else {
returnVal.Body = "error creating token"
returnVal.StatusCode = 500
}
} else {
fmt.Println("Hello Lambda")
token, err := jwt.Parse(passedToken, func(token *jwt.Token) (interface{}, error) {
return []byte(signingKey), nil
})
if err == nil && token.Valid {
claims := token.Claims.(jwt.MapClaims)
// TODO test for presence of claim
returnVal.Body = claims["foo"].(string)
} else {
returnVal.Body = "jwt not valid or missing required claim"
returnVal.StatusCode = 400
}
}
return returnVal, nil
}
func ExampleNew(mySigningKey []byte) (string, error) {
// Create the token
token := jwt.New(jwt.SigningMethodHS256)
// Set some claims
claims := make(jwt.MapClaims)
claims["foo"] = "bar"
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
token.Claims = claims
// Sign and get the complete encoded token as a string
tokenString, err := token.SignedString(mySigningKey)
return tokenString, err
}