Created
October 2, 2018 08:25
-
-
Save srbry/666ac79ad4311e8f0989003aa34cdfe5 to your computer and use it in GitHub Desktop.
Golang lambda authorizer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"strings" | |
"github.com/aws/aws-lambda-go/events" | |
"github.com/aws/aws-lambda-go/lambda" | |
) | |
func handler(request events.APIGatewayCustomAuthorizerRequest) (events.APIGatewayCustomAuthorizerResponse, error) { | |
token := request.AuthorizationToken | |
tokenSlice := strings.Split(token, " ") | |
var bearerToken string | |
if len(tokenSlice) > 1 { | |
bearerToken = tokenSlice[len(tokenSlice)-1] | |
} | |
if bearerToken != "hello" { | |
return events.APIGatewayCustomAuthorizerResponse{}, errors.New("Unauthorized") | |
} | |
return generatePolicy("user", "Allow", request.MethodArn), nil | |
} | |
func main() { | |
lambda.Start(handler) | |
} | |
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}, | |
}, | |
}, | |
} | |
} | |
return authResponse | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment