douzhanlie9209 2017-02-18 23:18
浏览 34
已采纳

无法使用基本身份验证保护大猩猩/多路复用子路由

I am trying to create routes using gorilla/mux, some of which should be protected by basic auth and others shouldn't. Specifically, every route under /v2 should require basic auth, but the routes under /health should be publicly accessible.

As you can see below, I can wrap each of my /v2 route handlers with BasicAuth(), but that's against the DRY principle, and also error prone, not to mention the security implications of forgetting to wrap one of those handlers.

I have the following output from curl. All but the last one is as I expect. One should not be able to GET /smallcat without authentication.

$ curl localhost:3000/health/ping
"PONG"
$ curl localhost:3000/health/ping/
404 page not found
$ curl localhost:3000/v2/bigcat
Unauthorised.
$ curl apiuser:apipass@localhost:3000/v2/bigcat
"Big MEOW"
$ curl localhost:3000/v2/smallcat
"Small Meow"

Here's the complete code. I believe I need to fix the v2Router definition somehow, but fail to see how.

package main

import (
    "crypto/subtle"
    "encoding/json"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func endAPICall(w http.ResponseWriter, httpStatus int, anyStruct interface{}) {

    result, err := json.MarshalIndent(anyStruct, "", "  ")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.WriteHeader(httpStatus)

    w.Write(result)
}

func BasicAuth(handler http.HandlerFunc, username, password, realm string) http.HandlerFunc {

    return func(w http.ResponseWriter, r *http.Request) {

        user, pass, ok := r.BasicAuth()

        if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(password)) != 1 {
            w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
            w.WriteHeader(401)
            w.Write([]byte("Unauthorised.
"))
            return
        }

        handler(w, r)
    }
}

func routers() *mux.Router {
    username := "apiuser"
    password := "apipass"

    noopHandler := func(http.ResponseWriter, *http.Request) {}

    topRouter := mux.NewRouter().StrictSlash(false)
    healthRouter := topRouter.PathPrefix("/health/").Subrouter()
    v2Router := topRouter.PathPrefix("/v2").HandlerFunc(BasicAuth(noopHandler, username, password, "Provide username and password")).Subrouter()

    healthRouter.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
        endAPICall(w, 200, "PONG")
    })

    v2Router.HandleFunc("/smallcat", func(w http.ResponseWriter, r *http.Request) {
        endAPICall(w, 200, "Small Meow")
    })

    bigMeowFn := func(w http.ResponseWriter, r *http.Request) {
        endAPICall(w, 200, "Big MEOW")
    }

    v2Router.HandleFunc("/bigcat", BasicAuth(bigMeowFn, username, password, "Provide username and password"))

    return topRouter
}

func main() {
    if r := routers(); r != nil {
        log.Fatal("Server exited:", http.ListenAndServe(":3000", r))
    }
}
  • 写回答

1条回答 默认 最新

  • douji5746 2017-02-19 23:18
    关注

    I achieved the expected behavior by using negroni. If the BasicAuth() call fails, none of the route handlers under /v2 are invoked.

    The working code is in a Gist (with revisions, for those interested) here: https://gist.github.com/gurjeet/13b2f69af6ac80c0357ab20ee24fa575

    Per SO convention, though, here's the complete code:

    package main
    
    import (
        "crypto/subtle"
        "encoding/json"
        "log"
        "net/http"
    
        "github.com/gorilla/mux"
        "github.com/urfave/negroni"
    )
    
    func endAPICall(w http.ResponseWriter, httpStatus int, anyStruct interface{}) {
    
        result, err := json.MarshalIndent(anyStruct, "", "  ")
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
    
        w.WriteHeader(httpStatus)
        w.Write(result)
    }
    
    func BasicAuth(w http.ResponseWriter, r *http.Request, username, password, realm string) bool {
    
        user, pass, ok := r.BasicAuth()
    
        if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(password)) != 1 {
            w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
            w.WriteHeader(401)
            w.Write([]byte("Unauthorised.
    "))
            return false
        }
    
        return true
    }
    
    func routers() *mux.Router {
        username := "apiuser"
        password := "apipass"
    
        v2Path := "/v2"
        healthPath := "/health"
    
        topRouter := mux.NewRouter().StrictSlash(true)
        healthRouter := mux.NewRouter().PathPrefix(healthPath).Subrouter().StrictSlash(true)
        v2Router := mux.NewRouter().PathPrefix(v2Path).Subrouter().StrictSlash(true)
    
        healthRouter.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
            endAPICall(w, 200, "PONG")
        })
    
        v2Router.HandleFunc("/smallcat", func(w http.ResponseWriter, r *http.Request) {
            endAPICall(w, 200, "Small Meow")
        })
    
        bigMeowFn := func(w http.ResponseWriter, r *http.Request) {
            endAPICall(w, 200, "Big MEOW")
        }
    
        v2Router.HandleFunc("/bigcat", bigMeowFn)
    
        topRouter.PathPrefix(healthPath).Handler(negroni.New(
            /* Health-check routes are unprotected */
            negroni.Wrap(healthRouter),
        ))
    
        topRouter.PathPrefix(v2Path).Handler(negroni.New(
            negroni.HandlerFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
                if BasicAuth(w, r, username, password, "Provide user name and password") {
                    /* Call the next handler iff Basic-Auth succeeded */
                    next(w, r)
                }
            }),
            negroni.Wrap(v2Router),
        ))
    
        return topRouter
    }
    
    func main() {
        if r := routers(); r != nil {
            log.Fatal("Server exited:", http.ListenAndServe(":3000", r))
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)