英文:
How to check authentication for hundreds and thousands of API endpoints?
问题
我目前正在使用Golang(使用Gorilla框架)构建一个Web应用程序,并已经实现了一些API端点。然而,我注意到每次我实现一个像下面这样的函数时:
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {}
我都必须在处理程序函数的主体中添加以下函数来检查请求是否经过授权:
func checkAuthorizedUser(r *http.Request) error {
uid, err := CheckRequestUser(r.Cookie("uid"))
if err != nil {
return errors.New("无法找到uid的cookie值")
}
if !IsValidUser(uid.Value) {
return errors.New("无效的用户")
}
return nil
}
目前我必须在每个处理程序函数中添加checkAuthorizedUser()
,而且到目前为止我已经有很多处理程序函数了。我想知道是否有一种更好的方法来检查客户端是否有权限访问某个特定的端点,而不是在每个处理程序函数中显式地检查身份验证。
英文:
I am currently building a web application in golang (with Gorilla) and have implemented a handful of API endpoints. However, I noticed that every time I implement a function like
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {}
I have to add the function below to the body of handler functions to check if request is authorized:
func checkAuthorizedUser (r * http.Request) error {
uid, err := CheckRequestUser (r.Cookie("uid"))
if err != nil {
return errors.New("Can't find cookie value for uid")
}
if !IsValidUser (uid.Value) {
return errors.New("Not a valid user")
}
return nil
}
What happens to me right now is that I have to add checkAuthorizedUser()
to every handler function, and I have already have a lot of handler functions so far. I wonder if there is a better way to check whether a client is authorized to access certain endpoint other than explicitly checking authentication in every handler function.
答案1
得分: 6
大猩猩有一个你可以使用的路由器。然后,你可以用身份验证检查包装路由器。类似下面的代码可以工作:
func checkPermissions(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
authCheck := true // 实现实际的检查逻辑
if authCheck {
w.WriteError(w, 400, "error")
return
}
h.ServeHTTP(w, r)
}
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/products", ProductsHandler)
r.HandleFunc("/articles", ArticlesHandler)
http.Handle("/", checkPermissions(r))
}
支持的链接:
https://godoc.org/github.com/gorilla/mux#NewRouter
https://github.com/gorilla/mux
英文:
Gorilla has a router you can use. You can then wrap the router with authentication checking. Something like this would work:
func checkPermissions(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
authCheck := true //implement the actual checking
if authCheck {
w.WriteError(w, 400, "error")
return
}
h.ServeHttp(w, r)
}
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/products", ProductsHandler)
r.HandleFunc("/articles", ArticlesHandler)
http.Handle("/", checkPermissions(r))
}
Supporting links:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论