1

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?

Temp O'rary
  • 5,366
  • 13
  • 49
  • 109
  • 1
    maybe this project can help: https://github.com/koajs/csrf – jackmis Jan 18 '21 at 08:48
  • @jackmis Thank you. I've gone through the details mentioned in the link above however, I've several questions in my mind now. 1. Are you required to set the session keys? 2. Are you required to set the session support? 3. For the first API call (such as login), how will the user get the CSRF token to be shared with server in the following calls? Hence, probably an example could help – Temp O'rary Jan 18 '21 at 09:11
  • Also the example given in the github link talks only about form based request but how to implement an API? – Temp O'rary Jan 18 '21 at 09:13
  • I am trying to implement this in a JWT based application – Temp O'rary Jan 18 '21 at 09:23
  • I did not familiar with that project and node.js. As I known, to prevent CSRF, we have to generate a parameter (a token) that attackers cannot predict, and then submit a request with the parameter, and verify the request through verify the parameter. For your questions, I guess: 1) no (I guess koa-csrf has its way to manage it); 2) yes (so that koa-csrf can verify the token); 3) I found this in Koajs project: https://github.com/koajs/examples/blob/master/csrf/app.js – jackmis Jan 18 '21 at 09:36
  • If you don't use cookies or sessions, you probably don't need CSRF tokens. – Evert Feb 03 '21 at 06:55

1 Answers1

0

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).

Dharman
  • 30,962
  • 25
  • 85
  • 135
RuiSiang
  • 154
  • 6