我编写了一些中间件来检查以确保 JWT 令牌有效:
func JwtVerify(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
//Get the token from the header
header := r.Header.Get("Authorization")
//If Authorization is empty, return a 403
if header == "" {
rw.WriteHeader(http.StatusForbidden)
json.NewEncoder(rw).Encode(ErrorMsg{ Message: "Missing Authentication Token" })
return
}
header = strings.Split(header, "Bearer ")[1]
token, err := jwt.Parse(header, func(token *jwt.Token) (i interface{}, err error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// TODO: REMOVE THE SECRET
return []byte("MyTestSecret"), nil
})
// Return the error
if err != nil {
rw.WriteHeader(http.StatusForbidden)
json.NewEncoder(rw).Encode(ErrorMsg{Message: err.Error()})
return
}
if token.Valid {
log.Println("JWT Token is valid")
next.ServeHTTP(rw, r)
}
})
}
我已经尝试为此编写一些测试,但我只能掌握我哪里出错了,测试应该失败,因为令牌无效但它仍然通过:
func TestJwtVerify(t *testing.T) {
token := "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODcwNTIzMTcsImV4cCI6MTU4NzA1MjkxNywic2Vzc2lvbi1kYXRhIjoiVGVzdC5NY1Rlc3RGYWNlQG1haWwuY29tIn0.f0oM4fSH_b1Xi5zEF0VK-t5uhpVidk5HY1O0EGR4SQQ"
req, err := http.NewRequest("GET", "/jwt", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", token)
testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Response.StatusCode == 403 {
t.Fatalf("Response should be 200 for a valid JWT Token")
}
})
rw := httptest.NewRecorder()
handler := JwtVerify(testHandler)
handler.ServeHTTP(rw, req)
}
有人可以解释我要去哪里错了吗?