加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
csrf_test.go 1.83 KB
一键复制 编辑 原始数据 按行查看 历史
aesoper 提交于 2020-05-20 15:06 . 添加日志中间件
/**
* @Author: aesoper
* @Description:
* @File: csrf_test
* @Version: 1.0.0
* @Date: 2020/5/19 21:06
*/
package gin_middleware
import (
"encoding/base64"
"fmt"
"gitee.com/aesoper/utils"
"gitee.com/gin-ecosystem/gin-middleware/consts"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestNewCSRF(t *testing.T) {
e := gin.New()
e.GET("/", NewCSRF(CSRFConfig{
Skipper: DefaultSkipper,
QueryAllowHosts: nil,
QueryAllowPattern: nil,
}))
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(consts.HeaderReferer, "http://my11sql.com")
resp := httptest.NewRecorder()
e.ServeHTTP(resp, req)
assert.Equal(t, resp.Result().StatusCode, http.StatusForbidden)
e.GET("/referer", NewCSRF(CSRFConfig{
Skipper: DefaultSkipper,
QueryAllowHosts: func() []string {
return []string{"my11sql.com"}
},
QueryAllowPattern: nil,
}))
req = httptest.NewRequest(http.MethodGet, "/referer", nil)
req.Header.Set(consts.HeaderReferer, "http://my11sql.com")
resp = httptest.NewRecorder()
e.ServeHTTP(resp, req)
assert.Equal(t, resp.Result().StatusCode, http.StatusOK)
e.GET("/token", NewCSRF(CSRFConfig{
Skipper: DefaultSkipper,
QueryAllowHosts: func() []string {
return []string{"my11sql.com"}
},
QueryAllowPattern: nil,
Validator: DefaultTokenValidator,
}))
req = httptest.NewRequest(http.MethodGet, "/token", nil)
req.Header.Set(consts.HeaderReferer, "http://my11sql.com")
input := fmt.Sprintf("%s-%d-%s", defaultCsrfSecret, time.Now().Unix(), utils.GenerateRandomStrings(8))
encodeString := base64.StdEncoding.EncodeToString([]byte(input))
req.Header.Set(consts.HeaderXCSRFToken, encodeString)
resp = httptest.NewRecorder()
e.ServeHTTP(resp, req)
assert.Equal(t, resp.Result().StatusCode, http.StatusOK)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化