访问基本身份验证凭据

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

Accessing Basic Auth credentials

问题

我正在使用GoLang开发一个API。所有对该API的调用都将包含一个public_key(用户名),有些还会在Authorization头中包含一个private_key(密码)。

我正在尝试找出如何访问Auth头的详细信息,以便我可以将凭据与数据库进行比对。

我正在使用Julien Schmidt的路由器和Alice来链接中间件。我目前的设置如下:

func main() {
    session, err := mgo.Dial("conn-string")
    if err != nil {
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)

    c := appContext{session.DB("db-name")}
    commonHandlers := alice.New(context.ClearHandler)
    router := NewRouter()
    router.Get("/", commonHandlers.Append(basicAuthHandler).ThenFunc(c.mainHandler))

    http.ListenAndServe(":5000", router)
}

但是我不确定如何继续编写下面的basicAuthHandler函数。如果public_key存在,我需要检查它是否有效。如果包含private_key,也需要进行相同的检查。

func basicAuthHandler(next http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {

    }

    return http.HandlerFunc(fn)
}
英文:

I'm working on an API using GoLang. All calls to this API will contain a public_key (username) and some will also contain a private_key (password) in the Authorization header.

I'm trying to figure out how to access the Auth header details so that I can check the credentials against a database.

I'm using Julien Schmidt's router and Alice to chain middleware. My setup so far is:

func main() {
    session, err := mgo.Dial("conn-string")
	if err != nil {
		panic(err)
	}
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)

	c := appContext{session.DB("db-name")}
	commonHandlers := alice.New(context.ClearHandler)
	router := NewRouter()
	router.Get("/", commonHandlers.Append(basicAuthHandler).ThenFunc(c.mainHandler))

	http.ListenAndServe(":5000", router)
}

but I'm not sure how to continue with the basicAuthHandler function below. If the public_key is present I need to check that it's valid. The same for the private_key if that's included.

func basicAuthHandler(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {

	}

	return http.HandlerFunc(fn)
}

答案1

得分: 4

尝试在请求上运行BasicAuth函数:

user, password, ok := r.BasicAuth()
if !ok {
  // 无法获取基本身份验证凭据
}
英文:

Try running the function BasicAuth on the request:

user, password, ok := r.BasicAuth()
if !ok {
  // could not get basic authentication credentials
}

huangapple
  • 本文由 发表于 2015年5月19日 21:48:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/30327588.html
匿名

发表评论

匿名网友

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

确定