我是 Golang 的新初学者,我开始使用 JWT 学习 Gorilla/Mux。
我刚刚成功注册用户到 MongoDB,然后登录。我用Postman来测试。但是当我尝试浏览受保护的路线时。我在验证中收到错误“缺少身份验证令牌”。
邮递员如何获得浏览受保护路由的授权?
下面是注册和登录的代码:
路由器功能
func Router() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
router.Use(CommonMiddleware)
//router.HandleFunc("/", middleware.TestAPI).Methods("GET", "OPTIONS")
router.HandleFunc("/register", middleware.RegisterHandler).Methods("POST", "OPTIONS")
router.HandleFunc("/login", middleware.LoginHandler).Methods("POST", "OPTIONS")
secure := router.PathPrefix("/auth").Subrouter()
secure.Use(auth.JwtVerify)
secure.HandleFunc("/api/task", middleware.GetAllTask).Methods("GET", "OPTIONS")
secure.HandleFunc("/api/task", middleware.CreateTask).Methods("POST", "OPTIONS")
secure.HandleFunc("/api/task/{id}", middleware.TaskComplete).Methods("PUT", "OPTIONS")
secure.HandleFunc("/api/undoTask/{id}", middleware.UndoTask).Methods("PUT", "OPTIONS")
secure.HandleFunc("/api/deleteTask/{id}", middleware.DeleteTask).Methods("DELETE", "OPTIONS")
secure.HandleFunc("/api/deleteAllTask", middleware.DeleteAllTask).Methods("DELETE", "OPTIONS")
return router
}
func CommonMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
next.ServeHTTP(w, r)
})
}
注册功能
func RegisterHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user models.User
body, _ := ioutil.ReadAll(r.Body)
err := json.Unmarshal(body, &user)
var res models.ResponseResult
if err != nil {
res.Error = err.Error()
json.NewEncoder(w).Encode(res)
return
}
湖上湖
肥皂起泡泡
相关分类