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

Function Test_CSRF_ExpiredToken_WithSession

middleware/csrf/csrf_test.go:460–535  ·  view source on GitHub ↗

go test -run Test_CSRF_ExpiredToken_WithSession

(t *testing.T)

Source from the content-addressed store, hash-verified

458
459// go test -run Test_CSRF_ExpiredToken_WithSession
460func Test_CSRF_ExpiredToken_WithSession(t *testing.T) {
461 t.Parallel()
462
463 // session store
464 store := session.NewStore(session.Config{
465 Extractor: extractors.FromCookie("_session"),
466 })
467
468 // fiber instance
469 app := fiber.New()
470
471 // fiber context
472 ctx := &fasthttp.RequestCtx{}
473 defer app.ReleaseCtx(app.AcquireCtx(ctx))
474
475 // get session
476 sess, err := store.Get(app.AcquireCtx(ctx))
477 require.NoError(t, err)
478 require.True(t, sess.Fresh())
479
480 // get session id
481 newSessionIDString := sess.ID()
482 require.NoError(t, sess.Save())
483
484 app.AcquireCtx(ctx).Request().Header.SetCookie("_session", newSessionIDString)
485
486 // middleware config
487 config := Config{
488 Session: store,
489 IdleTimeout: 1 * time.Second,
490 }
491
492 // middleware
493 app.Use(New(config))
494
495 app.Post("/", func(c fiber.Ctx) error {
496 return c.SendStatus(fiber.StatusOK)
497 })
498
499 h := app.Handler()
500
501 // Generate CSRF token
502 ctx.Request.Header.SetMethod(fiber.MethodGet)
503 ctx.Request.Header.SetCookie("_session", newSessionIDString)
504 h(ctx)
505 token := string(ctx.Response.Header.Peek(fiber.HeaderSetCookie))
506 for header := range strings.SplitSeq(token, ";") {
507 if strings.Split(utils.TrimSpace(header), "=")[0] == ConfigDefault.CookieName {
508 token = strings.Split(header, "=")[1]
509 break
510 }
511 }
512
513 // Use the CSRF token
514 ctx.Request.Reset()
515 ctx.Response.Reset()
516 ctx.Request.Header.SetMethod(fiber.MethodPost)
517 ctx.Request.Header.Set(HeaderName, token)

Callers

nothing calls this directly

Calls 15

GetMethod · 0.95
NewStoreFunction · 0.92
FromCookieFunction · 0.92
ReleaseCtxMethod · 0.80
AcquireCtxMethod · 0.80
HandlerMethod · 0.80
SetMethodMethod · 0.80
NewFunction · 0.70
NewMethod · 0.65
FreshMethod · 0.65
RequestMethod · 0.65
UseMethod · 0.65

Tested by

no test coverage detected