【发布时间】:2019-04-05 02:03:32
【问题描述】:
是否有更有效的方法来验证某些句柄请求的用户?现在我正在调用一个函数来根据请求令牌进行身份验证,但我正在为每个句柄函数执行此操作。
func GetCompanies(w http.ResponseWriter, r *http.Request) {
//Authentication
token := r.Header.Get("Authorization")
err := auth.AuthenticateUser(token)
if err != nil {
if custom, ok := err.(*errors.MyErrorType); ok {
fmt.Println(custom.Error())
w.WriteHeader(custom.Code)
_ = json.NewEncoder(w).Encode("Error: " + custom.Msg)
} else {
fmt.Println(err)
w.WriteHeader(500)
}
return
}
//If user is authenticated do other stuff
}
我尝试过使用中间件,但它适用于每个句柄函数。我希望未经身份验证的用户访问某些 API
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
fmt.Println(r.URL)
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
func HandleFunctions() {
//Init Router
r := mux.NewRouter()
r.Use(loggingMiddleware)
//API Paths that do not require Auth
r.HandleFunc("/login", handlers.Authenticate).Methods("POST")
//API Paths that require auth
r.HandleFunc("/stuff", handlers.PostThings).Methods("POST")
}
我还希望将来能够实现用户角色,以便根据安全权限不同的路径可用或不可用。
最有效的方法是什么?
【问题讨论】: