cookie
Description
Extracts a cookie with a given name from a request or otherwise rejects the request with a MissingCookieRejection
MissingCookieRejection
if the cookie is missing.
Use the optionalCookie directive instead if you want to support missing cookies in your inner route.
Example
- Scala
-
source
val route = cookie("userName") { nameCookie => complete(s"The logged in user is '${nameCookie.value}'") } // tests: Get("/") ~> Cookie("userName" -> "paul") ~> route ~> check { responseAs[String] shouldEqual "The logged in user is 'paul'" } // missing cookie Get("/") ~> route ~> check { rejection shouldEqual MissingCookieRejection("userName") } Get("/") ~> Route.seal(route) ~> check { responseAs[String] shouldEqual "Request is missing required cookie 'userName'" }
- Java
-
source
import static akka.http.javadsl.server.Directives.complete; import static akka.http.javadsl.server.Directives.cookie; final Route route = cookie("userName", nameCookie -> complete("The logged in user is '" + nameCookie.value() + "'") ); // tests: testRoute(route).run(HttpRequest.GET("/").addHeader(Cookie.create("userName", "paul"))) .assertEntity("The logged in user is 'paul'"); // missing cookie runRouteUnSealed(route, HttpRequest.GET("/")) .assertRejections(Rejections.missingCookie("userName")); testRoute(route).run(HttpRequest.GET("/")) .assertEntity("Request is missing required cookie 'userName'");