83 lines
2.4 KiB
Go
83 lines
2.4 KiB
Go
package jwt
|
|
|
|
import (
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// TestSignParseRoundTrip 验收:生成 Token 可正确解析(含 roles/permissions)。
|
|
func TestSignParseRoundTrip(t *testing.T) {
|
|
m := NewManager("day17-secret", time.Hour)
|
|
tok, err := m.Sign(1001, "alice", []string{"ops", "service"}, []string{"account:read", "channel:write"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if tok == "" {
|
|
t.Fatal("令牌为空")
|
|
}
|
|
claims, err := m.Parse(tok)
|
|
if err != nil {
|
|
t.Fatalf("解析失败: %v", err)
|
|
}
|
|
if claims.AccountID != 1001 || claims.Username != "alice" {
|
|
t.Fatalf("账户字段 = %+v", claims)
|
|
}
|
|
if len(claims.Roles) != 2 || claims.Roles[0] != "ops" {
|
|
t.Errorf("roles = %v", claims.Roles)
|
|
}
|
|
if len(claims.Permissions) != 2 || claims.Permissions[1] != "channel:write" {
|
|
t.Errorf("permissions = %v", claims.Permissions)
|
|
}
|
|
if claims.Issuer != "go-sms" || claims.Subject != "1001" {
|
|
t.Errorf("注册字段: issuer=%s sub=%s", claims.Issuer, claims.Subject)
|
|
}
|
|
if claims.ExpiresAt.Before(time.Now()) {
|
|
t.Error("过期时间应在未来")
|
|
}
|
|
}
|
|
|
|
// TestParseExpired 过期令牌拒绝(直接构造负 TTL,绕过构造器默认值)。
|
|
func TestParseExpired(t *testing.T) {
|
|
m := &Manager{Secret: "s", TTL: -time.Minute, Issuer: "go-sms"}
|
|
tok, _ := m.Sign(1, "u", []string{"customer"}, nil)
|
|
if _, err := m.Parse(tok); err == nil {
|
|
t.Fatal("过期令牌应解析失败")
|
|
}
|
|
}
|
|
|
|
// TestParseWrongSecret 错误密钥拒绝。
|
|
func TestParseWrongSecret(t *testing.T) {
|
|
tok, _ := NewManager("right", time.Hour).Sign(1, "u", []string{"admin"}, nil)
|
|
if _, err := NewManager("wrong", time.Hour).Parse(tok); err == nil {
|
|
t.Fatal("错误密钥应解析失败")
|
|
}
|
|
}
|
|
|
|
// TestParseGarbage 垃圾串/空令牌拒绝。
|
|
func TestParseGarbage(t *testing.T) {
|
|
m := NewManager("s", time.Hour)
|
|
for _, bad := range []string{"", "not.a.jwt", "a.b.c"} {
|
|
if _, err := m.Parse(bad); err == nil {
|
|
t.Errorf("垃圾串 %q 应解析失败", bad)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestSignValidation 入参校验。
|
|
func TestSignValidation(t *testing.T) {
|
|
m := NewManager("s", time.Hour)
|
|
if _, err := m.Sign(1, "", []string{"admin"}, nil); err == nil {
|
|
t.Error("空 username 应报错")
|
|
}
|
|
if _, err := m.Sign(1, "u", nil, nil); err == nil {
|
|
t.Error("空 roles 应报错")
|
|
}
|
|
}
|
|
|
|
// TestDefaultTTL 默认 TTL。
|
|
func TestDefaultTTL(t *testing.T) {
|
|
if got := NewManager("s", 0).Validity(); got != 2*time.Hour {
|
|
t.Errorf("默认 TTL = %v, 期望 2h", got)
|
|
}
|
|
}
|