119 lines
3.3 KiB
Go
119 lines
3.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
const testSecret = "day9-test-secret"
|
|
|
|
// newAuthRouter 构建带 JWT 保护路由的测试引擎。
|
|
func newAuthRouter() *gin.Engine {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
api := r.Group("/api/v1", AuthJWT(testSecret))
|
|
api.GET("/me", func(c *gin.Context) {
|
|
v, _ := c.Get(ContextKeyClaims)
|
|
claims := v.(*Claims)
|
|
c.JSON(200, gin.H{"username": claims.Username, "roles": claims.Roles})
|
|
})
|
|
return r
|
|
}
|
|
|
|
// TestAuthJWT_ValidToken 验证有效 Token 放行且 Claims 可用。
|
|
func TestAuthJWT_ValidToken(t *testing.T) {
|
|
r := newAuthRouter()
|
|
tok, err := SignAccessToken(testSecret, 1001, "alice", "admin", time.Minute)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/me", nil)
|
|
req.Header.Set("Authorization", "Bearer "+tok)
|
|
r.ServeHTTP(w, req)
|
|
|
|
if w.Code != 200 || w.Body.String() != `{"roles":["admin"],"username":"alice"}` {
|
|
t.Fatalf("有效 Token 应放行: code=%d body=%s", w.Code, w.Body.String())
|
|
}
|
|
}
|
|
|
|
// TestAuthJWT_InvalidToken 验收项:无效 Token 返回 401。
|
|
func TestAuthJWT_InvalidToken(t *testing.T) {
|
|
r := newAuthRouter()
|
|
cases := []struct {
|
|
name string
|
|
auth string
|
|
}{
|
|
{"缺失", ""},
|
|
{"非 Bearer", "Basic dXNlcjpwYXNz"},
|
|
{"垃圾串", "Bearer not.a.jwt"},
|
|
{"错误签名", "Bearer " + mustSign("wrong-secret")},
|
|
}
|
|
for _, tc := range cases {
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/me", nil)
|
|
if tc.auth != "" {
|
|
req.Header.Set("Authorization", tc.auth)
|
|
}
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != http.StatusUnauthorized {
|
|
t.Errorf("%s: 状态码 = %d, 期望 401", tc.name, w.Code)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestAuthJWT_ExpiredToken 验证过期 Token 返回 401。
|
|
func TestAuthJWT_ExpiredToken(t *testing.T) {
|
|
r := newAuthRouter()
|
|
tok, err := SignAccessToken(testSecret, 1, "bob", "user", -time.Minute) // 已过期
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/me", nil)
|
|
req.Header.Set("Authorization", "Bearer "+tok)
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != http.StatusUnauthorized {
|
|
t.Fatalf("过期 Token 应 401, 实际 %d", w.Code)
|
|
}
|
|
}
|
|
|
|
// TestRequirePermission 验证 Casbin 预留接口:checker 拒绝 → 403;nil → 放行。
|
|
func TestRequirePermission(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
deny := func(*Claims, string, string) bool { return false }
|
|
allow := func(*Claims, string, string) bool { return true }
|
|
|
|
tok, _ := SignAccessToken(testSecret, 1, "u", "viewer", time.Minute)
|
|
hit := func(checker PermissionChecker) int {
|
|
r := gin.New()
|
|
r.GET("/res", AuthJWT(testSecret), RequirePermission(checker, "sms", "send"), func(c *gin.Context) {
|
|
c.Status(200)
|
|
})
|
|
req := httptest.NewRequest(http.MethodGet, "/res", nil)
|
|
req.Header.Set("Authorization", "Bearer "+tok)
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
return w.Code
|
|
}
|
|
if hit(deny) != http.StatusForbidden {
|
|
t.Error("checker 拒绝应 403")
|
|
}
|
|
if hit(allow) != 200 {
|
|
t.Error("checker 放行应 200")
|
|
}
|
|
if hit(nil) != 200 {
|
|
t.Error("nil checker(未接入 Casbin)应放行")
|
|
}
|
|
}
|
|
|
|
// mustSign 用指定密钥签发(错误签名用例)。
|
|
func mustSign(secret string) string {
|
|
tok, _ := SignAccessToken(secret, 1, "x", "x", time.Minute)
|
|
return tok
|
|
}
|