-
Notifications
You must be signed in to change notification settings - Fork 573
Expand file tree
/
Copy pathexample_apigateway_custom_authorizer_test.go
More file actions
56 lines (50 loc) · 1.83 KB
/
example_apigateway_custom_authorizer_test.go
File metadata and controls
56 lines (50 loc) · 1.83 KB
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
package events_test
import (
"context"
"errors"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
// This is a simple TOKEN authorizer example to demonstrate how to use an authorization
// token to allow or deny a request. In this example, the caller named "user" is allowed to invoke
// a request if the client-supplied token value is "allow". The caller is not allowed to invoke
// the request if the token value is "deny". If the token value is "Unauthorized", the function
// returns the "Unauthorized" error with an HTTP status code of 401. For any other token value,
// the authorizer returns an "Invalid token" error.
func ExampleAPIGatewayCustomAuthorizerRequest() {
lambda.Start(func(ctx context.Context, event *events.APIGatewayCustomAuthorizerRequest) (*events.APIGatewayCustomAuthorizerResponse, error) {
token := event.AuthorizationToken
switch strings.ToLower(token) {
case "allow":
return generatePolicy("user", "Allow", event.MethodArn), nil
case "deny":
return generatePolicy("user", "Deny", event.MethodArn), nil
case "unauthorized":
return nil, errors.New("Unauthorized")
default:
return nil, errors.New("Error: Invalid token")
}
})
}
func generatePolicy(principalID, effect, resource string) *events.APIGatewayCustomAuthorizerResponse {
authResponse := &events.APIGatewayCustomAuthorizerResponse{PrincipalID: principalID}
if effect != "" && resource != "" {
authResponse.PolicyDocument = events.APIGatewayCustomAuthorizerPolicy{
Version: "2012-10-17",
Statement: []events.IAMPolicyStatement{
{
Action: []string{"execute-api:Invoke"},
Effect: effect,
Resource: []string{resource},
},
},
}
}
authResponse.Context = map[string]interface{}{
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true,
}
return authResponse
}