如何使用Golang Gin创建一个用于RESTful API的身份验证模型?

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

How to create a authentication model to restful API using golang gin?

问题

我希望为我的RESTful API创建一个身份验证模型。希望使用API令牌,并且我在Web服务中使用MVC,我创建了一个名为auth.go的控制器,代码如下:

package controllers

import (
    "github.com/gin-gonic/gin"
    "os"
)

type AdsControllerAuth struct {

}

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

        if token == "" {
            respondWithError(401, "API token required", c)
            return
        }

        if token != os.Getenv("API_TOKEN") {
            respondWithError(401, "Invalid API token", c)
            return
        }

        c.Next()
    }
}

func respondWithError(code int, message string, c *gin.Context) {
    resp := map[string]string{"error": message}

    c.JSON(code, resp)
    //c.Abort(code)
}

目前它还不能正常工作,有人可以帮忙解决这个问题吗?或者有没有可以参考的示例?

英文:

I hope to create a authentication model to my restful API. Hope to use API token and I'm using MVC in web service and I created a auth.go controller like this.

package controllers

import (
	
	"github.com/gin-gonic/gin"
    "os"
	//"github.com/jinzhu/gorm"

)

type AdsControllerAuth struct {
  
}


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

    if token == "" {
      respondWithError(401, "API token required", c)
      return 
    }

    if token != os.Getenv("API_TOKEN") {
      respondWithError(401, "Invalid API token", c)
      return
    }

    c.Next()
  }
}

func respondWithError(code int,message string,c *gin.Context) {
  resp := map[string]string{"error": message}

  c.JSON(code, resp)
  //c.Abort(code)
}

It doesn't working for now can some one help do this or is there are any examples to refer?

答案1

得分: 10

我自己编写了一个中间件来检查令牌,代码如下:

package main

import (
	"github.com/gin-gonic/gin"
)

// JWTAuthMiddleware 中间件
func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		validateToken(c)
		c.Next()
	}
}

func validateToken(c *gin.Context) {
	token := c.Request.Header.Get("X-Auth-Token")

	if token == "" {
		c.AbortWithStatus(401)
	} else if checkToken(token) {
		c.Next()
	} else {
		c.AbortWithStatus(401)
	}
}

在这个示例中,我使用了 Header 而不是 FormValue。

可以尝试使用 Chrome DHC 扩展来进行测试:https://chrome.google.com/webstore/detail/dhc-rest-client/aejoelaoggembcahagimdiliamlcdmfm

英文:

I made my own middleware to check token like below:

package main

import (
	"github.com/gin-gonic/gin"
)

//JWTAuthMiddleware middleware
func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		validateToken(c)
		c.Next()
	}
}

func validateToken(c *gin.Context) {
	token := c.Request.Header.Get("X-Auth-Token")

	if token == "" {
		c.AbortWithStatus(401)
	} else if checkToken(token) {
		c.Next()
	} else {
		c.AbortWithStatus(401)
	}
}

In the example, I'm using Header instead of FormValue.

Try out Chrome DHC extension to test: https://chrome.google.com/webstore/detail/dhc-rest-client/aejoelaoggembcahagimdiliamlcdmfm

huangapple
  • 本文由 发表于 2016年3月21日 12:10:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/36122999.html
匿名

发表评论

匿名网友

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

确定