MCPcopy
hub / github.com/gofiber/fiber / Test_CSRF_WithSession_Middleware

Function Test_CSRF_WithSession_Middleware

middleware/csrf/csrf_test.go:353–413  ·  view source on GitHub ↗

go test -run Test_CSRF_WithSession_Middleware

(t *testing.T)

Source from the content-addressed store, hash-verified

351
352// go test -run Test_CSRF_WithSession_Middleware
353func Test_CSRF_WithSession_Middleware(t *testing.T) {
354 t.Parallel()
355 app := fiber.New()
356
357 // session mw
358 smh, sstore := session.NewWithStore()
359
360 // csrf mw
361 cmh := New(Config{
362 Session: sstore,
363 })
364
365 app.Use(smh)
366
367 app.Use(cmh)
368
369 app.Get("/", func(c fiber.Ctx) error {
370 sess := session.FromContext(c)
371 sess.Set("hello", "world")
372 return c.SendStatus(fiber.StatusOK)
373 })
374
375 app.Post("/", func(c fiber.Ctx) error {
376 sess := session.FromContext(c)
377 if sess.Get("hello") != "world" {
378 return c.SendStatus(fiber.StatusInternalServerError)
379 }
380 return c.SendStatus(fiber.StatusOK)
381 })
382
383 h := app.Handler()
384 ctx := &fasthttp.RequestCtx{}
385
386 // Generate CSRF token and session_id
387 ctx.Request.Header.SetMethod(fiber.MethodGet)
388 h(ctx)
389
390 csrfCookie := fasthttp.AcquireCookie()
391 csrfCookie.SetKey(ConfigDefault.CookieName)
392 require.True(t, ctx.Response.Header.Cookie(csrfCookie))
393 csrfToken := string(csrfCookie.Value())
394 require.NotEmpty(t, csrfToken)
395 fasthttp.ReleaseCookie(csrfCookie)
396
397 sessionCookie := fasthttp.AcquireCookie()
398 sessionCookie.SetKey("session_id")
399 require.True(t, ctx.Response.Header.Cookie(sessionCookie))
400 sessionID := string(sessionCookie.Value())
401 require.NotEmpty(t, sessionID)
402 fasthttp.ReleaseCookie(sessionCookie)
403
404 // Use the CSRF token and session_id
405 ctx.Request.Reset()
406 ctx.Response.Reset()
407 ctx.Request.Header.SetMethod(fiber.MethodPost)
408 ctx.Request.Header.Set(HeaderName, csrfToken)
409 ctx.Request.Header.SetCookie(ConfigDefault.CookieName, csrfToken)
410 ctx.Request.Header.SetCookie("session_id", sessionID)

Callers

nothing calls this directly

Calls 15

NewWithStoreFunction · 0.92
FromContextFunction · 0.92
HandlerMethod · 0.80
SetMethodMethod · 0.80
NewFunction · 0.70
NewMethod · 0.65
UseMethod · 0.65
GetMethod · 0.65
SetMethod · 0.65
SendStatusMethod · 0.65
PostMethod · 0.65
CookieMethod · 0.65

Tested by

no test coverage detected