我想通过jwt身份验证来测试受保护的路由。
已经尝试接收响应并尝试传递令牌,但是它仅返回401作为代码响应。
包裹路线
import (
"fmt"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
)
func performRequest(r http.Handler, method, path string, t *testing.T) *httptest.ResponseRecorder {
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InJ1aWJsYWVzZUBnbWFpbC5jb20iLCJleHAiOjE1NTk0MjQxMjIsIm9yaWdfaWF0IjoxNTU5NDIwNTIyfQ.kdIRkLjRc63VQvDcHECId45_8rlCr8QlAmVBcEG2tlE"
w := httptest.NewRecorder()
req, _ := http.NewRequest(method, path, nil)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token))
r.ServeHTTP(w, req)
assert.Equal(t, w.Code, http.StatusOK)
return w
}
func TestStartRouter(t *testing.T) {
// Assert we encoded correctly,
// the request gives a 200
// Perform a GET request with that handler.
router := StartRouter()
w := performRequest(router, "GET", "/",t)
assert.Equal(t, http.StatusOK, w.Code)
w = performRequest(router, "POST", "/api/v1/signin",t)
assert.Equal(t, http.StatusOK, w.Code)
w = performRequest(router, "POST", "/api/v1/signup",t)
assert.Equal(t, http.StatusOK, w.Code)
w = performRequest(router, "GET", "/user",t)
assert.Equal(t, http.StatusOK, w.Code)
w = performRequest(router, "GET", "/user/id",t)
assert.Equal(t, http.StatusOK, w.Code)
w = performRequest(router, "GET", "/customer",t)
assert.Equal(t, http.StatusOK, w.Code)
w = performRequest(router, "GET", "/customer/id",t)
assert.Equal(t, http.StatusOK, w.Code)
}
目前,当我运行go test时,我只会得到401代码,但想获得http响应代码200。
答案 0 :(得分:1)
仅使用验证令牌的函数,这是jwt-go
的示例func isValidToken(tokenString, yourSecret string) bool {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(yourSecret), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return true
}
return false
}
答案 1 :(得分:0)
当然,这取决于您使用的软件包,但是我看不到处理程序内部对令牌的任何测试。它位于标题内,仅此而已。
也许您可以看看我如何为我的JWT包测试JWT包装器。您可以在
找到它