我正在使用 AWS Cognito 對(duì)我的用戶進(jìn)行身份驗(yàn)證,一旦通過身份驗(yàn)證,他們就可以調(diào)用我的 API (API Gateway + Lambda)。我正在使用無服務(wù)器框架完成所有這些工作。一旦通過身份驗(yàn)證,當(dāng)他們調(diào)用需要此身份驗(yàn)證的端點(diǎn)時(shí),我的 lambda 將通過request.RequestContext.Authorizer["claims"]. 我有創(chuàng)建一個(gè)身份驗(yàn)證中間件以將當(dāng)前用戶注入上下文的想法。但我確定我做錯(cuò)了什么(或者可以改進(jìn))。怎么運(yùn)行的:我的 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) }}型號(hào)/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}我有兩個(gè)問題:這是定義接收函數(shù)并返回另一個(gè)函數(shù)的函數(shù)(身份驗(yàn)證函數(shù))的正確方法嗎?因?yàn)樗唛L了,我覺得這是錯(cuò)誤的。有沒有辦法增加ctx一個(gè)user屬性?我正在嘗試的方式,我看到了錯(cuò)誤ctx.user undefined (type context.Context has no field or method user)。
如何在 AWS Lambda 中創(chuàng)建身份驗(yàn)證中間件
慕的地6264312
2023-05-04 17:01:20