英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论