亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang - 如何獲得 mux 的授權?

Golang - 如何獲得 mux 的授權?

Go
月關寶盒 2023-07-26 16:33:20
我是 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  }
查看完整描述

2 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

由于您正在檢查請求標頭中的令牌x-access-token,因此需要在發送請求時添加相同的令牌。這可以在 Postman 中輕松完成,如下所示 -

http://img1.sycdn.imooc.com//64c0da9e0001cf4e22341288.jpg

我用過的路由器是 -


包主


func router() *mux.Router {

    router := mux.NewRouter().StrictSlash(true)

    secure := router.PathPrefix("/auth").Subrouter()

    secure.Use(auth.JwtVerify)

    secure.HandleFunc("/api", middleware.ApiHandler).Methods("GET")

    return router

}


func main() {

    r := router()

    http.ListenAndServe(":8080", r)

}

我使用的中間件是 -


包授權


func JwtVerify(next http.Handler) http.Handler {

    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        var header = r.Header.Get("x-access-token")


        json.NewEncoder(w).Encode(r)

        header = strings.TrimSpace(header)


        if header == "" {

            w.WriteHeader(http.StatusForbidden)

            json.NewEncoder(w).Encode("Missing auth token")

            return

        } else {

            json.NewEncoder(w).Encode(fmt.Sprintf("Token found. Value %s", header))

        }

        next.ServeHTTP(w, r)

    })

}

處理程序是 -


封裝中間件


func ApiHandler(w http.ResponseWriter, r *http.Request) {

    w.WriteHeader(http.StatusOK)

    w.Header().Set("Content-Type", "application/json")

    json.NewEncoder(w).Encode("SUCCESS!")

    return

}


查看完整回答
反對 回復 2023-07-26
?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

您可以在授權部分傳遞令牌:


http://img1.sycdn.imooc.com//64c0dab500015b1308950349.jpg

查看完整回答
反對 回復 2023-07-26
  • 2 回答
  • 0 關注
  • 168 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號