Comments (7)
@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.
I'll throw an example together soon.
from csrf.
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.
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.
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.
Awesome, thanks for the example. It's very helpful
from csrf.
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)
- option to disable ?_csrf= support HOT 1
- tests randomly fail HOT 2
- why change tokens on every request HOT 1
- Upgrading to Koa2.0 HOT 5
- Why assertCsrf method given a body value? HOT 1
- why deprecate csrf@2 HOT 8
- Importing koa-csrf in node 6 HOT 1
- csrf(app) csrf is not a function
- Add option for verifying csrf token in certain types request only HOT 3
- I always get "Invalid CSRF token" following the example HOT 1
- CSRF is not a constructor HOT 2
- Use with koa-router HOT 1
- Seems like `context.csrf` is being set without me doing anything HOT 6
- Question: omitted options do not set defaults in this.tokens HOT 1
- Can i disable CSRF check for some routes? HOT 6
- Enable csrf per route example HOT 1
- Use of koa-session instead koa-generic-session HOT 2
- Add csrf token in ctx.state HOT 4
- Exclude route HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from csrf.