Go中要求HTTP基本身份验证的惯用方式? [英] Idiomatic way of requiring HTTP Basic Auth in Go?

查看:40
本文介绍了Go中要求HTTP基本身份验证的惯用方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:

我正在使用Gorilla的多路复用器作为路由器来构建REST API.

I'm building a REST API using Gorilla's mux as the router.

我想知道如何通过简单的HTTP Basic Auth保护特定的路由.我不需要从文件或任何外部源中读取凭据,我真的只想通过硬编码的HTTP Basic Auth用户名和密码来保护选定的路由.

I'm wondering how I can protect specific routes with simple HTTP Basic Auth. I don't have a need to read the credentials from a file or any external source, I really just want to protect selected routes by a hard coded HTTP Basic Auth username and password.

问题:

Go中惯用的方式是什么?大猩猩提供任何使它变得更容易的东西吗?如果您能提供几行代码,那就太好了.

What is the idiomatic way of doing so in Go? Does Gorilla offer anything to make it more easy? If you could provide a few lines of code, that would be just wonderful.

推荐答案

将几个答案合并到一个简单的复制/粘贴操作中:

Combining a couple of answers into an easy copy/paste:

// BasicAuth wraps a handler requiring HTTP basic auth for it using the given
// username and password and the specified realm, which shouldn't contain quotes.
//
// Most web browser display a dialog with something like:
//
//    The website says: "<realm>"
//
// Which is really stupid so you may want to set the realm to a message rather than
// an actual realm.
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.\n"))
            return
        }

        handler(w, r)
    }
}

...

http.HandleFunc("/", BasicAuth(handleIndex, "admin", "123456", "Please enter your username and password for this site"))

请注意, subtle.ConstantTimeCompare()仍取决于长度,因此,如果您这样做,攻击者可能会计算出用户名和密码的长度.要解决这个问题,您可以对它们进行散列或添加固定的延迟.

Note that subtle.ConstantTimeCompare() still depends on the length, so it is probably possible for attackers to work out the length of the username and password if you do it like this. To get around that you could hash them or add a fixed delay.

这篇关于Go中要求HTTP基本身份验证的惯用方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆