如何在 Gin Gonic 的 Go 中使用中间件进行授权?

huangapple go评论79阅读模式
英文:

how to do authorization with middleware - gin gonic go

问题

我正在学习如何在gin框架中使用中间件,并且我遇到了一个问题。

我希望只有当我的Test函数满足TokenAuthMiddleware函数的要求时,它才会在Postman中显示。

但是无论我的请求体是否填充,我的Test函数都会被调用(无论是否进行身份验证)。如何解决这个问题?
我希望我的Test函数只在经过中间件后才显示。

我尝试了以下代码:

package main

import (
	"log"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
)

func TokenAuthMiddleware() gin.HandlerFunc {
	err := godotenv.Load(".env")
	if err != nil {
		log.Fatal("Erro ao ler variaveis de ambiente")
	}
	requiredToken := os.Getenv("API_TOKEN")

	if requiredToken == "" {
		log.Fatal("Por favor, defina a variavel API_TOKEN")
	}

	return func(c *gin.Context) {
		token := c.Request.FormValue("api_token")

		if token == "" {
			c.JSON(http.StatusBadRequest, gin.H{"message": "Token deve ser preenchido"})

		} else if token != requiredToken {
			c.JSON(http.StatusBadRequest, gin.H{"message": "Token invalido"})

		}
		c.Next()
	}

}

func Teste(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"sucess": "so beautiful",
	})
}

func main() {

	api := gin.New()

	v1 := api.Group("v1")
	v1.Use(TokenAuthMiddleware())
	v1.GET("/", Teste)

	api.Run()
}

非常感谢您的提问!

英文:

i am learning to use middleware with gin framework and i am facing a problem

I want my Test function to be displayed in postman only if it has the requirements of my func TokenAuthMiddleware

but regardless of whether my body is filled in or not, my test function is being called (with or without authentication) how to resolve this?
i want my Test func to be displayed only after going through the middlewate

I tried something like this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

package main

import (
	&quot;log&quot;
	&quot;net/http&quot;
	&quot;os&quot;

	&quot;github.com/gin-gonic/gin&quot;
	&quot;github.com/joho/godotenv&quot;
)

func TokenAuthMiddleware() gin.HandlerFunc {
	err := godotenv.Load(&quot;.env&quot;)
	if err != nil {
		log.Fatal(&quot;Erro ao ler variaveis de ambiente&quot;)
	}
	requiredToken := os.Getenv(&quot;API_TOKEN&quot;)

	if requiredToken == &quot;&quot; {
		log.Fatal(&quot;Por favor, defina a variavel API_TOKEN&quot;)
	}

	return func(c *gin.Context) {
		token := c.Request.FormValue(&quot;api_token&quot;)

		if token == &quot;&quot; {
			c.JSON(http.StatusBadRequest, gin.H{&quot;message&quot;: &quot;Token deve ser preenchido&quot;})

		} else if token != requiredToken {
			c.JSON(http.StatusBadRequest, gin.H{&quot;message&quot;: &quot;Token invalido&quot;})

		}
		c.Next()
	}

}

func Teste(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		&quot;sucess&quot;: &quot;so beautiful&quot;,
	})
}

func main() {

	api := gin.New()

	v1 := api.Group(&quot;v1&quot;)
	v1.Use(TokenAuthMiddleware())
	v1.GET(&quot;/&quot;, Teste)

	api.Run()
}

<!-- end snippet -->

Thank you very much in advance

答案1

得分: 1

你总是调用c.Next(),它会继续执行中间件链或执行处理程序。当令牌不正确时,你需要避免调用它。

func TokenAuthMiddleware() gin.HandlerFunc {
    err := godotenv.Load(".env")
    if err != nil {
        log.Fatal("Erro ao ler variaveis de ambiente")
    }
    requiredToken := os.Getenv("API_TOKEN")

    if requiredToken == "" {
        log.Fatal("Por favor, defina a variavel API_TOKEN")
    }

    return func(c *gin.Context) {
        token := c.Request.FormValue("api_token")

        if token == "" {
            c.JSON(http.StatusBadRequest, gin.H{"message": "Token deve ser preenchido"})
            return
        }
        if token != requiredToken {
            c.JSON(http.StatusBadRequest, gin.H{"message": "Token invalido"})
            return
        }

        c.Next()
    }
}

以上是要翻译的内容。

英文:

You're always calling c.Next(), which continues on with the middleware chain or executes the handler. You need avoid calling it when the token is incorrect.

func TokenAuthMiddleware() gin.HandlerFunc {
    err := godotenv.Load(&quot;.env&quot;)
    if err != nil {
        log.Fatal(&quot;Erro ao ler variaveis de ambiente&quot;)
    }
    requiredToken := os.Getenv(&quot;API_TOKEN&quot;)

    if requiredToken == &quot;&quot; {
        log.Fatal(&quot;Por favor, defina a variavel API_TOKEN&quot;)
    }

    return func(c *gin.Context) {
        token := c.Request.FormValue(&quot;api_token&quot;)

        if token == &quot;&quot; {
            c.JSON(http.StatusBadRequest, gin.H{&quot;message&quot;: &quot;Token deve ser preenchido&quot;})
            return
        }
        if token != requiredToken {
            c.JSON(http.StatusBadRequest, gin.H{&quot;message&quot;: &quot;Token invalido&quot;})
            return
        }

        c.Next()
    }

}

huangapple
  • 本文由 发表于 2023年1月4日 22:55:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75007230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定