Go语言 如何在Gin框架中使用Auth0授权?

xzabzqsa  于 2023-03-10  发布在  Go
关注(0)|答案(1)|浏览(224)

我尝试在我的Golang(Gin)后端使用Auth 0授权,以限制对授权方的请求,我以前为Django做过这个,但我不能让它在Gin和Golang上工作。
我试过了所有能找到的指南,没有一个能用,包括auth 0 docs found here
我的主。走

package main

import (
   "StatsMicro/controller"
   "StatsMicro/middleware"
   "StatsMicro/models"
   "github.com/gin-gonic/gin"
)

func main() {
   println("HERE")
   var r *gin.Engine = gin.Default()
   r.Use(middleware.EnsureValidToken())
   println("pasted engine")
   models.ConnectDatabase()
   println("PAST ENDPOINTS")
   r.POST("/update", controller.AliveUpdate)
   r.POST("/ErrorCreate", controller.ErrorCreate)
   r.POST("/postCreate", controller.PsotCreated)

   r.GET("/user", controller.AliveGet)
   r.GET("/activeAll", controller.ActiveallTotal)
   r.GET("/postAll", controller.PostAllTotal)
   r.GET("/errorTotal", controller.ErrorAllTotal)
   r.GET("/error", controller.ErrorGet)
   r.GET("/post", controller.PostGet)
   err := r.Run("127.0.0.1:2003")
   if err != nil {
      return
   }

}

我的 JWT :

package middleware

import (
   "context"
   "log"
   "net/http"
   "net/url"
   "os"
   "time"

   "github.com/auth0/go-jwt-middleware/v2"
   "github.com/auth0/go-jwt-middleware/v2/jwks"
   "github.com/auth0/go-jwt-middleware/v2/validator"
)

// CustomClaims contains custom data we want from the token.
type CustomClaims struct {
   Scope string `json:"scope"`
}

// Validate does nothing for this example, but we need
// it to satisfy validator.CustomClaims interface.
func (c CustomClaims) Validate(ctx context.Context) error {
   return nil
}

// EnsureValidToken is a middleware that will check the validity of our JWT.
func EnsureValidToken() func(next http.Handler) http.Handler {
   issuerURL, err := url.Parse("https://" + os.Getenv("AUTH0_DOMAIN") + "/")
   if err != nil {
      log.Fatalf("Failed to parse the issuer url: %v", err)
   }

   provider := jwks.NewCachingProvider(issuerURL, 5*time.Minute)

   jwtValidator, err := validator.New(
      provider.KeyFunc,
      validator.RS256,
      issuerURL.String(),
      []string{os.Getenv("AUTH0_AUDIENCE")},
      validator.WithCustomClaims(
         func() validator.CustomClaims {
            return &CustomClaims{}
         },
      ),
      validator.WithAllowedClockSkew(time.Minute),
   )
   if err != nil {
      log.Fatalf("Failed to set up the jwt validator")
   }

   errorHandler := func(w http.ResponseWriter, r *http.Request, err error) {
      log.Printf("Encountered error while validating JWT: %v", err)

      w.Header().Set("Content-Type", "application/json")
      w.WriteHeader(http.StatusUnauthorized)
      w.Write([]byte(`{"message":"Failed to validate JWT."}`))
   }

   middleware := jwtmiddleware.New(
      jwtValidator.ValidateToken,
      jwtmiddleware.WithErrorHandler(errorHandler),
   )

   return func(next http.Handler) http.Handler {
      return middleware.CheckJWT(next)
   }
}

当我运行main.go时产生的错误如下:

main.go:13:8: cannot use middleware.EnsureValidToken() (value of type func(next http.Handler) http.Handler) as type gin.HandlerFunc in argument to r.Use

据我所知,这是因为它不是一个有效的ginHandlerFunc,如果是这样,我如何将它转换成一个有效的gin处理函数呢?
我尝试过使用网上的多个指南。其中一些是非常旧的版本,其他的就不起作用了。考虑到这一点的重要性,我宁愿不使用旧版本。
Dev.To guide-无法使其工作
GitHub-非常旧的版本
Medium-无法使其工作。

8zzbczxx

8zzbczxx1#

您的方法EnsureValidToken需要返回一个gin.HandlerFunc.您可能希望查看www.example.com中的Wrap函数https://github.com/gwatts/gin-adapter/blob/master/adapter.go#L62(尽管使用该模块可能更好)。
工作原理如下:

func EnsureValidToken() gin.HandlerFunc {
    issuerURL, err := url.Parse("https://" + os.Getenv("AUTH0_DOMAIN") + "/")
    if err != nil {
        log.Fatalf("Failed to parse the issuer url: %v", err)
    }

    provider := jwks.NewCachingProvider(issuerURL, 5*time.Minute)

    jwtValidator, err := validator.New(
        provider.KeyFunc,
        validator.RS256,
        issuerURL.String(),
        []string{os.Getenv("AUTH0_AUDIENCE")},
        validator.WithCustomClaims(
            func() validator.CustomClaims {
                return &CustomClaims{}
            },
        ),
        validator.WithAllowedClockSkew(time.Minute),
    )
    if err != nil {
        log.Fatalf("Failed to set up the jwt validator")
    }

    errorHandler := func(w http.ResponseWriter, r *http.Request, err error) {
        log.Printf("Encountered error while validating JWT: %v", err)

        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusUnauthorized)
        w.Write([]byte(`{"message":"Failed to validate JWT."}`))
    }

    middleware := jwtmiddleware.New(
        jwtValidator.ValidateToken,
        jwtmiddleware.WithErrorHandler(errorHandler),
    )

    return adapter.Wrap(middleware.CheckJWT)
}

要应用中间件:

r.Use(middleware.EnsureValidToken())

相关问题