Skip to content

Instantly share code, notes, and snippets.

@srbry
Created October 2, 2018 08:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save srbry/666ac79ad4311e8f0989003aa34cdfe5 to your computer and use it in GitHub Desktop.
Save srbry/666ac79ad4311e8f0989003aa34cdfe5 to your computer and use it in GitHub Desktop.
Golang lambda authorizer
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