代码拉取完成,页面将自动刷新
/**
* @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())
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。