The object passed to ctx parameter contains a cookie object that we can use to signed cookies with a password or secret key in view to identify unique user browser. It is very important for different purpose, for example a signed cookie could be used to authenticate user and allow him/her to login into forbidden areas, or it could be used to bypass authentication if a user is already authenticated.
“The context.cookies allows access to the values of cookies in the request, and allows cookies to be set in the response. It automatically secures cookies if the .keys property is set on the application. Because .cookies uses the web crypto APIs to sign and validate cookies, and those APIs work in an asynchronous way, the cookie APIs work in an asynchronous way,” wrote the team designing Oak framework in their GitHub.
It means that cookie could be signed using response object, and the signing is automatically carried out by Oak web crypto APIs when a password or secret key is passed to the constructor of the Application class. Moreover, signed cookie can be read, but the modification of the cookie in question requires the original password or secret key used to sign the cookie.
// app.js
import { Application } from "https://deno.land/x/oak/mod.ts"
const app = new Application({keys: ["secret1"]})
app.use(async (ctx) => {
const myCookie = await ctx.cookies.get("myCookie")
await ctx.cookies.set("myCookie", new Date().toISOString())
if (myCookie) {
ctx.response.body = `The cookie was set at ${myCookie}.`
} else {
ctx.response.body = `No cookie is set yet.`
}
})
app.addEventListener(
"listen",
(e) => console.log("Listening on http://localhost:8000")
)
await app.listen({ port: 8000})
// denon run --allow-net app.js
With the attempts to get the cookie using get( ) method, “if the applications .keys is set, then the cookie will be verified against a signed version of the cookie. If the cookie is valid, the promise will resolve with the value. If it is invalid, the cookie signature will be set to deleted on the response. If the cookie was not signed by the current key, it will be resigned and added to the response,” said Oak framework team.
When a cookie is set via set( ) method, “if the applications .keys is set, then the cookie will be signed and the signature added to the response. As the keys are signed asynchronously, awaiting the .set() method is advised,” added Oak framework team.