mirror of https://github.com/golang-jwt/jwt.git
79 lines
2.5 KiB
Go
79 lines
2.5 KiB
Go
package jwt
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"reflect"
|
|
"testing"
|
|
)
|
|
|
|
var jwtTestData = []struct {
|
|
name string
|
|
tokenString string
|
|
claims map[string]interface{}
|
|
valid bool
|
|
}{
|
|
{
|
|
"basic",
|
|
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
|
map[string]interface{}{"foo": "bar"},
|
|
true,
|
|
},
|
|
{
|
|
"basic invalid",
|
|
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
|
map[string]interface{}{"foo": "bar"},
|
|
false,
|
|
},
|
|
}
|
|
|
|
func TestJWT(t *testing.T) {
|
|
file, _ := os.Open("test/sample_key.pub")
|
|
buf := new(bytes.Buffer)
|
|
io.Copy(buf, file)
|
|
key := buf.Bytes()
|
|
file.Close()
|
|
|
|
for _, data := range jwtTestData {
|
|
token, err := Parse(data.tokenString, func(t *Token) ([]byte, error) { return key, nil })
|
|
|
|
if !reflect.DeepEqual(data.claims, token.Claims) {
|
|
t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims)
|
|
}
|
|
if data.valid && err != nil {
|
|
t.Errorf("[%v] Error while verifying token: %v", data.name, err)
|
|
}
|
|
if !data.valid && err == nil {
|
|
t.Errorf("[%v] Invalid token passed validation", data.name)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestParseRequest(t *testing.T) {
|
|
file, _ := os.Open("test/sample_key.pub")
|
|
buf := new(bytes.Buffer)
|
|
io.Copy(buf, file)
|
|
key := buf.Bytes()
|
|
file.Close()
|
|
|
|
// Bearer token request
|
|
for _, data := range jwtTestData {
|
|
r, _ := http.NewRequest("GET", "/", nil)
|
|
r.Header.Set("Authorization", fmt.Sprintf("Bearer %v", data.tokenString))
|
|
token, err := ParseFromRequest(r, func(t *Token) ([]byte, error) { return key, nil })
|
|
|
|
if !reflect.DeepEqual(data.claims, token.Claims) {
|
|
t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims)
|
|
}
|
|
if data.valid && err != nil {
|
|
t.Errorf("[%v] Error while verifying token: %v", data.name, err)
|
|
}
|
|
if !data.valid && err == nil {
|
|
t.Errorf("[%v] Invalid token passed validation", data.name)
|
|
}
|
|
}
|
|
}
|