Home > Backend Development > Golang > How to use middleware for authorization - gin gonic go

How to use middleware for authorization - gin gonic go

PHPz
Release: 2024-02-05 21:24:08
forward
1283 people have browsed it

如何使用中间件进行授权 - gin gonic go

Question content

I am learning to use middleware with the gin framework, but I encountered a problem

I want my test function to only show up in postman if it meets the requirements of my func tokenauthmiddleware

But my test function is called regardless of whether my body is filled in or not (with or without authentication) How to fix this? I want my test function to display

only after passing through the middle layer

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()
}
Copy after login

Thank you very much in advance


Correct answer


You always call c.next(), it will Continue processing the middleware chain or execute the handler. You need to 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()
    }

}
Copy after login

The above is the detailed content of How to use middleware for authorization - gin gonic go. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template