我有一个API,可以管理公司的各种工作,并使用不记名令牌授权 我希望用户从任务列表中选择可用任务之一,以便使用/ api / tasks / {task}网址,如下所示:/ api / tasks / checkaccount 如果给定的任务不在任务列表中,则返回无效的url。 是否可以通过validateMiddleware函数处理此工作?
我的startApi函数:
func (s *ApiServerStruct) Start(interval int) {
router := mux.NewRouter()
log.Println("Starting the Api")
log.Printf("Api Listen: %s\n", "127.0.0.1:8080")
router.HandleFunc("/api/customer/newcustomer", ValidateMiddleware(s.newcustomer)).Methods("POST")
router.HandleFunc("/api/customer/setsalary", ValidateMiddleware(s.SetSalary)).Methods("POST")
router.HandleFunc("/api/customer/listcustomers", ValidateMiddleware(s.ListCustomers)).Methods("GET")
router.HandleFunc("/api/customer/{login:0x[0-9a-fA-F]{40}}/newjob", ValidateMiddleware(s.NewJob)).Methods("POST")
router.HandleFunc("/api/tasks/{task}/setnewtask", ValidateMiddleware(s.SetNewTask)).Methods("POST")
还有一个validateMiddleware函数,该函数检查标头中的给定令牌是否有效:
func ValidateMiddleware(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
authorizationHeader := req.Header.Get("authorization")
if authorizationHeader != "" {
bearerToken := strings.Split(authorizationHeader, " ")
tempData := Data[bearerToken[1]]
secretKey := tempData["secretkey"]
if secretKey == "" {
json.NewEncoder(w).Encode(Exception{Message: "Invalid authorization token"})
return
}
if len(bearerToken) == 2 {
token, error := jwt.Parse(bearerToken[1], func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("There was an error")
}
return []byte(secretKey), nil
})
if error != nil {
json.NewEncoder(w).Encode(Exception{Message: error.Error()})
return
}
if token.Valid {
context.Set(req, "decoded", token.Claims)
next(w, req)
} else {
json.NewEncoder(w).Encode(Exception{Message: "Invalid authorization token"})
}
}
} else {
json.NewEncoder(w).Encode(Exception{Message: "An authorization header is required"})
}
})
}