我正在使用 AWS Cognito 對我的用戶進行身份驗證,一旦通過身份驗證,他們就可以調用我的 API (API Gateway + Lambda)。我正在使用無服務器框架完成所有這些工作。一旦通過身份驗證,當他們調用需要此身份驗證的端點時,我的 lambda 將通過request.RequestContext.Authorizer["claims"]. 我有創建一個身份驗證中間件以將當前用戶注入上下文的想法。但我確定我做錯了什么(或者可以改進)。怎么運行的:我的 lambda.go:package mainimport ( "context" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/company/api/middlewares")func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { fmt.Println(ctx.user) return events.APIGatewayProxyResponse{}, nil}func main() { lambda.Start( middlewares.Authentication(Handler), )}中間件/authentication.gopackage middlewaresimport ( "context" "github.com/aws/aws-lambda-go/events" "github.com/company/api/models")func Authentication(next func(context.Context, events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)) func(context.Context, events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { var user models.User return func(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { claims := request.RequestContext.Authorizer["claims"] // Find user by claims properties. if err := user.Current(claims); err != nil { return events.APIGatewayProxyResponse{}, err } ctx.user = user return next(ctx, request) }}型號/user.go:package modelsimport ( "github.com/jinzhu/gorm" "github.com/mitchellh/mapstructure")type User struct { gorm.Model // Override ID cause we are using cognito. Email string `gorm:"primary_key,not null"` Site Site}我有兩個問題:這是定義接收函數并返回另一個函數的函數(身份驗證函數)的正確方法嗎?因為它太冗長了,我覺得這是錯誤的。有沒有辦法增加ctx一個user屬性?我正在嘗試的方式,我看到了錯誤ctx.user undefined (type context.Context has no field or method user)。
如何在 AWS Lambda 中創建身份驗證中間件
慕的地6264312
2023-05-04 17:01:20