library-go/jwt/token_test.go

88 lines
2.3 KiB
Go
Raw Permalink Normal View History

2024-08-27 05:46:58 +00:00
package jwt
import (
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestGenerateAccessToken(t *testing.T) {
// 定義測試參數
token := Token{
ID: "12345",
ExpiresIn: int(time.Now().Add(1 * time.Hour).Unix()),
}
sign := "secret_sign"
data := map[string]string{
"role": "admin",
"uid": "user123",
}
issuer := "test_issuer"
// 調用生成 access token
accessToken, err := GenerateAccessToken(token, data, sign, issuer)
require.NoError(t, err)
require.NotEmpty(t, accessToken)
// 檢查 access token 是否可以解析
claims, err := ParseToken(accessToken, sign, true)
require.NoError(t, err)
// 驗證 Claims 是否正確
require.Equal(t, token.ID, claims["jti"])
require.Equal(t, issuer, claims["iss"])
require.Equal(t, "admin", claims["data"].(map[string]interface{})["role"])
require.Equal(t, "user123", claims["data"].(map[string]interface{})["uid"])
}
func TestParseToken(t *testing.T) {
// 測試生成並解析 token
token := Token{
ID: "67890",
ExpiresIn: int(time.Now().Add(2 * time.Hour).Unix()),
}
sign := "another_secret_sign"
data := map[string]string{
"role": "user",
"uid": "user456",
}
accessToken, err := GenerateAccessToken(token, data, sign, "example_issuer")
require.NoError(t, err)
require.NotEmpty(t, accessToken)
// 測試有驗證的解析
claims, err := ParseToken(accessToken, sign, true)
require.NoError(t, err)
require.Equal(t, "user", claims["data"].(map[string]interface{})["role"])
require.Equal(t, "user456", claims["data"].(map[string]interface{})["uid"])
// 測試不驗證的解析
claimsNoValidation, err := ParseToken(accessToken, sign, false)
require.NoError(t, err)
require.Equal(t, "user", claimsNoValidation["data"].(map[string]interface{})["role"])
}
func TestParseClaims(t *testing.T) {
// 測試生成並解析 claims
token := Token{
ID: "54321",
ExpiresIn: int(time.Now().Add(3 * time.Hour).Unix()),
}
sign := "test_sign"
data := map[string]string{
"role": "moderator",
"uid": "user789",
}
accessToken, err := GenerateAccessToken(token, data, sign, "sample_issuer")
require.NoError(t, err)
// 測試 claims 解析
parsedClaims, err := ParseClaims(accessToken, sign, true)
require.NoError(t, err)
require.Equal(t, "moderator", parsedClaims["role"])
require.Equal(t, "user789", parsedClaims["uid"])
}