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

Function Test_CSRF_WithSession

middleware/csrf/csrf_test.go:262–350  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

260}
261
262func Test_CSRF_WithSession(t *testing.T) {
263 t.Parallel()
264
265 // session store
266 store := session.NewStore(session.Config{
267 Extractor: extractors.FromCookie("_session"),
268 })
269
270 // fiber instance
271 app := fiber.New()
272
273 // fiber context
274 ctx := &fasthttp.RequestCtx{}
275 defer app.ReleaseCtx(app.AcquireCtx(ctx))
276
277 // get session
278 sess, err := store.Get(app.AcquireCtx(ctx))
279 require.NoError(t, err)
280 require.True(t, sess.Fresh())
281
282 // the session string is no longer be 123
283 newSessionIDString := sess.ID()
284 require.NoError(t, sess.Save())
285
286 app.AcquireCtx(ctx).Request().Header.SetCookie("_session", newSessionIDString)
287
288 // middleware config
289 config := Config{
290 Session: store,
291 }
292
293 // middleware
294 app.Use(New(config))
295
296 app.Post("/", func(c fiber.Ctx) error {
297 return c.SendStatus(fiber.StatusOK)
298 })
299
300 h := app.Handler()
301
302 methods := [5]string{fiber.MethodGet, fiber.MethodHead, fiber.MethodOptions, fiber.MethodTrace, fiber.MethodQuery}
303
304 for _, method := range methods {
305 // Generate CSRF token
306 ctx.Request.Header.SetMethod(fiber.MethodGet)
307 ctx.Request.Header.SetCookie("_session", newSessionIDString)
308 h(ctx)
309
310 // Without CSRF cookie
311 ctx.Request.Reset()
312 ctx.Response.Reset()
313 ctx.Request.Header.SetMethod(fiber.MethodPost)
314 ctx.Request.Header.SetCookie("_session", newSessionIDString)
315 h(ctx)
316 require.Equal(t, 403, ctx.Response.StatusCode())
317
318 // Empty/invalid CSRF token
319 ctx.Request.Reset()

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