dongzhang4301 2016-03-21 04:10
浏览 39

如何使用golang杜松子酒创建针对静态API的身份验证模型?

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条回答 默认 最新

  • douju1365 2016-04-01 14:35
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口