go test -run Test_CSRF_WithSession_Middleware
(t *testing.T)
| 351 | |
| 352 | // go test -run Test_CSRF_WithSession_Middleware |
| 353 | func 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) |
nothing calls this directly
no test coverage detected