如何在go-gin框架中验证API key ?



所以我目前有一个函数,将采取一个字符串APIKey检查它对我的MongoDB集合。如果没有找到(未验证),则返回false—如果找到用户,则返回true。然而,我的问题是我不确定如何将此与Gin POST路由集成。下面是我的代码:


import (
"context"
"fmt"
"log"
"os"
"github.com/gin-gonic/gin"
_ "github.com/joho/godotenv/autoload"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type User struct {
Name   string
APIKey string
}
func validateAPIKey(users *mongo.Collection, APIKey string) bool {
var user User
filter := bson.D{primitive.E{Key: "APIKey", Value: APIKey}}
if err := users.FindOne(context.TODO(), filter).Decode(&user); err != nil {
fmt.Printf("Found 0 results for API Key: %sn", APIKey)
return false
}
fmt.Printf("Found: %sn", user.Name)
return true
}
func handleUpload(c *gin.Context) {
}
func main() {
r := gin.Default()
api := r.Group("/api")
v1 := api.Group("/v1")
v1.POST("/upload", handleUpload)
mongoURI := os.Getenv("MONGO_URI")
mongoOptions := options.Client().ApplyURI(mongoURI)
client, err := mongo.Connect(context.TODO(), mongoOptions)
if err != nil {
log.Fatal(err, "Unable to access MongoDB server, exiting...")
}
defer client.Disconnect(context.TODO())
// users := client.Database("sharex_api").Collection("authorized_users") // commented out when testing to ignore unused warnings
r.Run(":8085")
}

validateAPIKey函数完全按照预期工作,如果单独测试,我只是不确定如何为特定端点(在本例中为/api/v1/upload)运行此函数并传递用户集合。

经过一番搜索,我找到了一个解决方案。我改变了我的validateAPIKey函数返回git.HandlerFunc。下面是代码:

func validateAPIKey(users *mongo.Collection) gin.HandlerFunc {
return func(c *gin.Context) {
var user authorizedUser
APIKey := c.Request.Header.Get("X-API-Key")
filter := bson.D{primitive.E{Key: "APIKey", Value: APIKey}}
if err := users.FindOne(context.TODO(), filter).Decode(&user); err != nil {
fmt.Printf("Found 0 results for API Key: %sn", APIKey)
c.JSON(http.StatusUnauthorized, gin.H{"status": 401, "message": "Authentication failed"})
return
}
return
}
}

对于路由,我有以下内容:

v1.POST("/upload", validateAPIKey(users), handleUpload)

相关内容

  • 没有找到相关文章

最新更新