Reputation: 5828
I know that Cross-Site Request Forgery (CSRF)
is an attack that forces an user to execute unintentional actions some web application in which they are already logged in.
I want to prevent CSRF on calls being made to my Koa.js based APIs and form submissions. This is a JWT based application.
Usually frameworks have plugins that prevent or secure against CSRF. However, how can you prevent such CSRF attacks when you are using Koa.js
? Are there any middlewares
in Koa that does this?
Upvotes: 1
Views: 1091
Reputation: 184
It is actually simple to write a middleware by yourself (I'll put an example here if I have time). Basically, the flow is as follows:
Generate a token and save it in the session (https://www.npmjs.com/package/koa-session) and place that token as a hidden field in the form. When the form is submitted, check if the token posted in the hidden field is the same as the one saved in the session. Be sure to regenerate a new token every request though.
An important point to notice is that the session token has to be either saved server-side or encrypted on the client-side or it'll be pointless. Simlpy using signed JWT tokens will not work in this scenario. If you want to use JWT tokens, you'll have to implement redis or something to save key-value pairs of (JWT-token:csrf-token).
Upvotes: 0