Skip to content

Instantly share code, notes, and snippets.

@IgorDePaula
Forked from srbry/main.go
Created Feb 22, 2021
Embed
What would you like to do?
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