doushijia5684 2019-06-02 13:41
浏览 127

如何在Go中测试身份验证JWT路由

I want to test protected routes in go with jwt authentication .

Already try to receive a response and try to pass a token, but its only returns 401 as code response .

package routes

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)

}

for now when i run go test, I only get code 401, but want to get http response code 200 .

  • 写回答

2条回答 默认 最新

  • dongxu1029 2019-06-02 16:36
    关注

    Surely it depends on your used packages, but I don't see any test of the token inside a handler. It's inside the header, but that's all.

    Maybe you take a look on how I test my JWT wrapper for my JWT packages. You find it at

    https://github.com/tideland/go/blob/170f9d31dde003d7fdab1f643119acb8f4e24879/net/webbox/wrapper_test.go#L197

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器