简体   繁体   中英

How to test authenticate JWT routes in go

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.

just use a function that's validates your token, here is an example with 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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM