Search code examples
gopostmango-gin

how to do authorization with middleware - gin gonic go


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:

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()
}

Thank you very much in advance


Solution

  • 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(".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()
        }
    
    }