问题
I am creating a keystone project and I need to provide allow or not allow users to access using the keystone signin. However, I found that keystoneJS sends a form data with email, password and csrf. This csrf is given to the user when he access to the login page.
Nevertheless, what I need to do is to comunicate externally to login the user, by using an API. How can I generate the _csrf? Is there another way then generate two requests?
Thanks
回答1:
@Sericaia, you didn't include any code or specifics on how you intend to implement your login page, so my answer will be a little vague.
Keystone has an internal API for handling CSRF token creation and validation. I don't think it's documented, but here's a gist of how it works.
In your route handler you can create a CSRF token key/value pair that you can then inject into your view locals and then use in your view template. You can do it manually like this.
app.get('/login', function (req, res) {
var keystone = require('keystone');
var csrfTokenKey = keystone.security.csrf.TOKEN_KEY;
var csrfTokenValue = keystone.security.csrf.getToken(req, res);
res.render('login', {
csrfTokenKey: csrfTokenKey,
csrfTokenValue: csrfTokenValue
});
});
Or you can use provided middleware.
// the middleware will automatically inject the CSRF token
// into res.locals[keystone.security.csrf.LOCAL_KEY]
app.get('/login', keystone.security.csrf.middleware.init, function(req, res) {
...
});
You can also validate the CSRF token received from the client. You can do it manually as follows:
app.post('/login', function(req, res) {
if (keystone.security.csrf.validate(req)) {
// CSRF is valid
...
} else {
// CSRF is not valid
...
}
});
Or you can use the provided middleware.
// the middleware will return 403 status with "CSRF token mismatch"
// of there's a error validating the CSRF token received
app.post('/login', keystone.security.csrf.middleware.validate, function(req, res) {
...
});
Hope this helps.
来源:https://stackoverflow.com/questions/29240757/keystonejs-signin