Refactor CSRF token (#32216)

This commit is contained in:
wxiaoguang 2024-10-10 11:48:21 +08:00 committed by GitHub
parent 368b0881f5
commit dd83cfcacc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
29 changed files with 90 additions and 126 deletions

View file

@ -486,23 +486,19 @@ func VerifyJSONSchema(t testing.TB, resp *httptest.ResponseRecorder, schemaFile
assert.True(t, result.Valid())
}
// GetCSRF returns CSRF token from body
// If it fails, it means the CSRF token is not found in the response body returned by the url with the given session.
// In this case, you should find a better url to get it.
func GetCSRF(t testing.TB, session *TestSession, urlStr string) string {
// GetUserCSRFToken returns CSRF token for current user
func GetUserCSRFToken(t testing.TB, session *TestSession) string {
t.Helper()
req := NewRequest(t, "GET", urlStr)
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
csrf := doc.GetCSRF()
require.NotEmpty(t, csrf)
return csrf
cookie := session.GetCookie("_csrf")
require.NotEmpty(t, cookie)
return cookie.Value
}
// GetCSRFFrom returns CSRF token from body
func GetCSRFFromCookie(t testing.TB, session *TestSession, urlStr string) string {
// GetUserCSRFToken returns CSRF token for anonymous user (not logged in)
func GetAnonymousCSRFToken(t testing.TB, session *TestSession) string {
t.Helper()
req := NewRequest(t, "GET", urlStr)
session.MakeRequest(t, req, http.StatusOK)
return session.GetCookie("_csrf").Value
resp := session.MakeRequest(t, NewRequest(t, "GET", "/user/login"), http.StatusOK)
csrfToken := NewHTMLParser(t, resp.Body).GetCSRF()
require.NotEmpty(t, csrfToken)
return csrfToken
}