question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How do I get the CSRF token from the request body?

See original GitHub issue

Looking at these lines: https://github.com/koajs/csrf/blob/master/src/index.js#L59-L60 when I’m debugging, ctx.request.body is always undefined. I don’t know why. Can anyone help?

Something else: at the same breakpoint as above, ctx.csrf IS defined. Should I just be using ctx.csrf as the token? I’m confused as to why ctx.csrf isn’t already treated as the token.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

4reactions
stephenmathiesoncommented, Oct 23, 2017

@joegalley super contrived example (will cleanup and add to the repo eventually):

const Koa = require('koa')
const Router = require('koa-router')
const session = require('koa-generic-session')
const bodyParser = require('koa-bodyparser')
const convert = require('koa-convert')
const CSRF = require('koa-csrf')

const app = new Koa();
const router = new Router()

app.keys = [ 'foo', 'bar' ];

app.use(bodyParser())
app.use(convert(session()));

router.get('/', (ctx, next) => {
  ctx.type = 'html'
  ctx.body = `
    <!doctype html>
    <html>
      <head>
        <title>koa-csrf example</title>
      </head>
      <body>
        <h1>koa-csrf example</h1>
        <form>
          <input type='hidden' name='_csrf' value='${ctx.csrf}' />
          <select>
            <option value='none'>no csrf</option>
            <option value='query'>query string csrf</option>
            <option value='body'>post body csrf</option>
            <option value='header'>header csrf</option>
          </select>
          <button type='submit'>submit</button>
        </form>
        <script>
          var form = document.querySelector('form')
          var select = form.querySelector('select')
          var csrf = form.querySelector('input[name="_csrf"]').value

          form.onsubmit = function (e) {
            e.preventDefault()

            var xhr = new XMLHttpRequest()
            var url = '/submit'
            var body

            var type = select.options[select.selectedIndex].value

            if (type === 'query') { // add the CSRF token to the query string when submitting the form
              url += '?_csrf=' + csrf
              xhr.open('POST', url)
            } else if (type === 'body') { // add the CSRF token in the POST body (requires using koa-bodyparser on the server)
              xhr.open('POST', url)
              xhr.setRequestHeader('content-type', 'application/json')
              body = JSON.stringify({ _csrf: csrf })
            } else if (type === 'header') { // add the CSRF token as a the header when submitting the form
              xhr.open('POST', url)
              xhr.setRequestHeader('x-csrf-token', csrf)
            } else if (type === 'none') { // do not add the CSRF token
              xhr.open('POST', url)
            }

            xhr.onreadystatechange = function (e) {
              if (xhr.readyState === XMLHttpRequest.DONE) {
                alert(xhr.responseText)
              }
            }

            xhr.send(body)
          }
        </script>
      </body>
    </html>
  `
})

router.post('/submit', (ctx, next) => {
  ctx.body = 'yay! you submitted a valid CSRF token!'
})

app.use(new CSRF())
app.use(router.routes())

app.listen(44567)
1reaction
stephenmathiesoncommented, Oct 23, 2017

I’ll throw an example together soon.

Read more comments on GitHub >

github_iconTop Results From Across the Web

CSRF tokens | Web Security Academy - PortSwigger
A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such...
Read more >
Is it a security risk to allow CSRF token to be sent in body OR ...
CSRF is about make a unsuspicious user post data to a server where the attacker believes the user is logged in.
Read more >
Cross-Site Request Forgery Prevention Cheat Sheet
The CSRF token can be transmitted to the client as part of a response payload, such as a HTML or JSON response. It...
Read more >
Integrating token-based Cross-Site Request Forgery (CSRF ...
The client acquires a new CSRF token from the server by calling the REST endpoint baseURL/v1/csrf/tokens. The server generates a new, unique CSRF...
Read more >
Performing a POST request with a csrf token
The csrf token is obtained by first logging in to Assets Server through a POST request. The response that is received will include...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found