GithubHelp home page GithubHelp logo

Comments (7)

stephenmathieson avatar stephenmathieson commented on May 2, 2024 5

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

from csrf.

stephenmathieson avatar stephenmathieson commented on May 2, 2024 1

I'll throw an example together soon.

from csrf.

stephenmathieson avatar stephenmathieson commented on May 2, 2024

Regarding ctx.request.body, see https://github.com/koajs/csrf/blob/2.x/index.js#L104-L106. It's provided by the bodyparser middleware. Note that you are not required to use the bodyparser middleware for koa-csrf to work. For some reason, when the next branch was merged, none of the helpful contextual comments were carried over. Sorry about that.

The particular line you've highlighted is checking to see if a _crsf field was provided in the body of the request. This is used to assert that a token was provided and is valid.

Closing for now. Reopen/respond if I haven't clarified this for you.

from csrf.

joegalley avatar joegalley commented on May 2, 2024

Since it seems like you're only looking for csrf in the request body, as a query param, or in a header, I can't actually get it to verify my token (since it's in ctx.csrf and not one of these places).

from csrf.

joegalley avatar joegalley commented on May 2, 2024

Is this the approach I should be taking to move the csrf variable from ctx to ctx.body (and thus have the koa-csrf middleware be able to read it?

From the README:

// your middleware here (e.g. parse a form submit)
app.use((ctx, next) => {

if (![ 'GET', 'POST' ].includes(ctx.method))
    return next();

  if (ctx.method === 'GET') {
    ctx.body = ctx.csrf;
    return;
  }

  ctx.body = 'OK';

});

I didn't put anything in my server's index.js file for csrf stuff, but it seemed to send a csrf token on every POST request anyway. So I'm not really sure if I need to add anything else..

I do think a "real" example would be helpful here

from csrf.

joegalley avatar joegalley commented on May 2, 2024

Awesome, thanks for the example. It's very helpful

from csrf.

joegalley avatar joegalley commented on May 2, 2024

Another question..

I'm using this with ReactJS, so I'm rendering React components via Ajax and I was thinking of adding the csrf token to the response body of my ajax requests, and putting the value into a hidden form field inside of my component. Does this make sense to do? Since I'm not rendering raw HTML and inserting the csrf token via a template variable, I can't think of any other good way to do this in React.

from csrf.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.