koajs / csrf

CSRF tokens for koa
MIT License
264 stars 32 forks source link

Seems like `context.csrf` is being set without me doing anything #41

Closed joegalley closed 7 years ago

joegalley commented 7 years ago

I am debugging my project and have a breakpoint set at this line: https://github.com/koajs/csrf/blob/master/src/index.js#L56

Now when I evaluate (ctx.csrf), I get a value back. However I am not sending a CSRF token anywhere in my application..all I've done is set Koa to use the CSRF middleare..I haven't embedded _csrf in a hidden form field anywhere, nor have I appended a csrf token to any of my requests. So my question is, how is ctx.csrf already set?

stephenmathieson commented 7 years ago

Yes, the token is set whether or not you send it. This library asserts that the token was provided by the user.

It's clear that a "real" example is necessary here. I'll see if I can throw something together in shortly.

joegalley commented 7 years ago

@stephenmathieson Awesome, thank you

joegalley commented 7 years ago

When you say this library asserts that the token "was provided by the user", this validation is happening when you compare the submitted csrf token to the ctx.session.secret, right? So is a new csrf token generated for every context, and validated against the session secret?

If this is the case, I don't see why we need to store the token client-side (in a hidden form field)

stephenmathieson commented 7 years ago

The token is salted with the secret. The token is unique per request/session. You need to pass the token to your client so it can send it back. The token validates that the user is who the user is claiming to be.

I think there's a misunderstanding of what this module helps you do. Are you familiar with what CSRF is? A good read/silly read is https://dev.to/rtfeldman/defense-against-the-dark-arts-csrf-attacks. I think it does a pretty good job at explaining what CSRF is/why you should protect against it.

joegalley commented 7 years ago

I understand what CSRF protection does, I think I'm confused as to how long one particular csrf token is supposed to last. Should I be sending a new token with every request, or could I save a token when first loading the site, and keep sending that token back with each request (for as long as the user's session lasts)?

stephenmathieson commented 7 years ago

The token is valid for the duration of the user’s session in SPAs and for each request otherwise. Basically any time we can create a new token, we will.