1 Star 3 Fork 2

gin-ecosystem/gin-middleware

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
jwt_test.go 2.16 KB
一键复制 编辑 原始数据 按行查看 历史
aesoper 提交于 2020-05-20 15:06 . 添加日志中间件
/**
* @Author: aesoper
* @Description:
* @File: jwt_test
* @Version: 1.0.0
* @Date: 2020/5/19 23:29
*/
package gin_middleware
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
)
func TestNewJwt(t *testing.T) {
e := gin.New()
entity := NewJwt(JwtConfig{
TokenLookup: "header:Authorization",
AuthScheme: "Bearer",
SigningKey: "1111",
Authenticator: func(ctx *gin.Context, claims jwt.MapClaims, token string) error {
fmt.Printf("claims %v\n token: %s\n", claims, token)
if userName, ok := claims["username"]; !ok {
return fmt.Errorf("用户%s未登录", userName)
}
return nil
},
Unauthorized: func(ctx *gin.Context, httpCode int, err error) {
ctx.String(httpCode, "用户未登录请先登陆")
},
})
// 登陆测试
e.POST("/doLogin", func(ctx *gin.Context) {
token, _, err := entity.GenerateJwtToken(map[string]interface{}{
"username": ctx.Query("username"),
"password": ctx.Query("password"),
})
if err != nil {
ctx.String(http.StatusUnauthorized, "你还未登录")
return
}
ctx.String(http.StatusOK, token)
})
req := httptest.NewRequest(http.MethodPost, "/doLogin?username=1&password=2", nil)
resp := httptest.NewRecorder()
e.ServeHTTP(resp, req)
assert.Equal(t, http.StatusOK, resp.Code)
assert.NotEmpty(t, resp.Body.String())
accesToken := resp.Body.String()
fmt.Printf("get accesToken : \n %s \n", accesToken)
// 登陆后获取信息测试
e.GET("/getInfo", entity.Middleware(), func(ctx *gin.Context) {
ctx.String(http.StatusOK, "success")
})
req = httptest.NewRequest(http.MethodGet, "/getInfo", nil)
req.Header.Set("Authorization", "Bearer "+accesToken)
resp = httptest.NewRecorder()
e.ServeHTTP(resp, req)
assert.Equal(t, "success", resp.Body.String())
fmt.Printf("======%s", resp.Body.String())
// 未登录测试
req = httptest.NewRequest(http.MethodGet, "/getInfo", nil)
// req.Header.Set("Authorization", "Bearer " + accesToken)
resp = httptest.NewRecorder()
e.ServeHTTP(resp, req)
assert.Equal(t, http.StatusUnauthorized, resp.Code)
fmt.Printf("======%s", resp.Body.String())
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/gin-ecosystem/gin-middleware.git
git@gitee.com:gin-ecosystem/gin-middleware.git
gin-ecosystem
gin-middleware
gin-middleware
master

搜索帮助