docs: How to send CSRF information to the server?
Type: docs
Platform: mobile browser
I am using oauth-phonegap to handle authentication. It seems to have gotten me to a decent point in prototyping, but I now need it to actually authenticate the user on my server. I am CCing @william26, whom I believe is the maintainer of oauth-phonegap and @dougwilson, whom I believe is the maintainer of the express middleware csurf. I am using both of these technologies they are actively involved in. I'm opening this up as an ionic issue, because I have yet to see documentation on handling authentication, and it would be nice for the community to have this available as a resource. I think, also, that this conversation might help steer any documentation that may come from this.
Update: looks like there is a blog post on this subject: http://ionicframework.com/blog/angularjs-authentication/ So maybe now this is hopefully more of a resource for someone else who may be experiencing similar difficulties.
I'm wondering how you ensure proper csrf information is sent to the server. Currently my login controller looks like this:
var app = angular.module('app');
app.controller('LoginCtrl', function($scope, $state, UserService, $http, $cookies) {
OAuth.initialize('LONG_STRING');
var token = null;
// fetch csrf session token from server
$http.get('http://api.example.com/oauth/token')
.success(function(generatedToken, status) {
return token = generatedToken;
}).error(function(errorMessage, status) {
return console.log("l8 LoginCtrl\n " + status + ": " + errorMessage);
});
// fired when user touches the Google login button
$scope.googleLogin = function() {
return OAuth.popup('google', {
cache: false,
state: token
}).done(function(result) {
// so far so good, but this is where the request is invalid
$http.post("http://api.example.com/oauth/signin")
.success(function(data, status) {
debugger;
}).error(function(data, status) {
debugger;
});
}).fail(function(error) {
return console.log('error: ', error);
});
};
It's when I send a POST request to /oauth/signin that my server is unhappy:
ForbiddenError: invalid csrf token
My express server code looks like this:
var MongoStore, app, bodyParser, compress, connectAssets, cookieParser, csrf, csrfProtection, errorHandler, express, expressValidator, flash, logger, methodOverride, mongoose, multer, oauth, passport, passportConf, parseForm, path, secrets, session;
express = require('express');
cookieParser = require('cookie-parser');
compress = require('compression');
session = require('express-session');
bodyParser = require('body-parser');
logger = require('morgan');
errorHandler = require('errorhandler');
methodOverride = require('method-override');
multer = require('multer');
MongoStore = require('connect-mongo')(session);
flash = require('express-flash');
path = require('path');
mongoose = require('mongoose');
passport = require('passport');
expressValidator = require('express-validator');
connectAssets = require('connect-assets');
csrf = require('csurf');
oauth = require('oauthio');
oauth.initialize('NE4HoArIyEc1uI70v5RZ5wIkM1U', '7Ow9lx7rfR6f5mrZDOyZebjw9fc');
csrfProtection = csrf({
cookie: true
});
parseForm = bodyparser.urlencoded({ extended: false })
secrets = require('./config/secrets');
passportConf = require('./config/passport');
app = express();
mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
console.error('MongoDB Connection Error. Please make sure that MongoDB is running.');
});
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compress());
app.use(connectAssets({
paths: [path.join(__dirname, 'public/css'), path.join(__dirname, 'public/js')]
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(multer({
dest: path.join(__dirname, 'uploads')
}));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
resave: true,
saveUninitialized: true,
secret: secrets.sessionSecret,
store: new MongoStore({
url: secrets.db,
autoReconnect: true
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(express["static"](path.join(__dirname, 'public'), {
maxAge: 31557600000
}));
app.use(csrf(), function(req, res, next) {
debugger;
res.cookie('csrf-token', req.csrfToken());
return next();
});
app.get('/oauth/token', csrfProtection, function(req, res) {
var token;
token = oauth.generateStateToken(req.session);
return res.send(token);
});
app.post("/oauth/signin", parseForm, csrfProtection, function(req, res) {
var code = req.body.data;
debugger;
oauth.auth("google", req.session, {
code: code
}).then(function(request_object) {
debugger;
return res.send(200, "The user is authenticated");
}).fail(function(e) {
debugger;
console.log(e);
return res.send(400, "Code is incorrect");
});
return res.redirect(req.session.returnTo || '/');
});
app.use(errorHandler());
app.listen(app.get("port"), function() {
console.log("Express server listening on port %d in %s mode", app.get("port"), app.get("env"));
});
module.exports = app;```
And here's the error code:
root@example:~/example-api# node index
Express server listening on port 3000 in development mode
GET /oauth/token 200 25.549 ms - 26
ForbiddenError: invalid csrf token
at verifytoken (/root/example-api/node_modules/csurf/index.js:263:11)
at csrf (/root/example-api/node_modules/csurf/index.js:93:7)
at Layer.handle [as handle_request] (/root/example-api/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/root/example-api/node_modules/express/lib/router/index.js:302:13)
at /root/example-api/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/root/example-api/node_modules/express/lib/router/index.js:321:12)
at next (/root/example-api/node_modules/express/lib/router/index.js:261:10)
at serveStatic (/root/example-api/node_modules/express/node_modules/serve-static/index.js:59:14)
at Layer.handle [as handle_request] (/root/example-api/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/root/example-api/node_modules/express/lib/router/index.js:302:13)
at /root/example-api/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/root/example-api/node_modules/express/lib/router/index.js:321:12)
at next (/root/example-api/node_modules/express/lib/router/index.js:261:10)
at /root/example-api/node_modules/express-flash/lib/express-flash.js:31:7
at /root/example-api/node_modules/express-flash/node_modules/connect-flash/lib/flash.js:21:5
at /root/example-api/node_modules/express-flash/lib/express-flash.js:22:5
at Layer.handle [as handle_request] (/root/example-api/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/root/example-api/node_modules/express/lib/router/index.js:302:13)
at /root/example-api/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/root/example-api/node_modules/express/lib/router/index.js:321:12)
at next (/root/example-api/node_modules/express/lib/router/index.js:261:10)
at SessionStrategy.strategy.pass (/root/example-api/node_modules/passport/lib/middleware/authenticate.js:318:9)
at SessionStrategy.authenticate (/root/example-api/node_modules/passport/lib/strategies/session.js:67:10)
at attempt (/root/example-api/node_modules/passport/lib/middleware/authenticate.js:341:16)
at authenticate (/root/example-api/node_modules/passport/lib/middleware/authenticate.js:342:7)
at Layer.handle [as handle_request] (/root/example-api/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/root/example-api/node_modules/express/lib/router/index.js:302:13)
at /root/example-api/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/root/example-api/node_modules/express/lib/router/index.js:321:12)
at next (/root/example-api/node_modules/express/lib/router/index.js:261:10)
at initialize (/root/example-api/node_modules/passport/lib/middleware/initialize.js:62:5)
at Layer.handle [as handle_request] (/root/example-api/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/root/example-api/node_modules/express/lib/router/index.js:302:13)
at /root/example-api/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/root/example-api/node_modules/express/lib/router/index.js:321:12)
at next (/root/example-api/node_modules/express/lib/router/index.js:261:10)
at session (/root/example-api/node_modules/express-session/index.js:386:7)
at Layer.handle [as handle_request] (/root/example-api/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/root/example-api/node_modules/express/lib/router/index.js:302:13)
at /root/example-api/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/root/example-api/node_modules/express/lib/router/index.js:321:12)
at next (/root/example-api/node_modules/express/lib/router/index.js:261:10)
at cookieParser (/root/example-api/node_modules/cookie-parser/index.js:34:14)
at Layer.handle [as handle_request] (/root/example-api/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/root/example-api/node_modules/express/lib/router/index.js:302:13)
at /root/example-api/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/root/example-api/node_modules/express/lib/router/index.js:321:12)
at next (/root/example-api/node_modules/express/lib/router/index.js:261:10)
at methodOverride (/root/example-api/node_modules/method-override/index.js:77:5)
at Layer.handle [as handle_request] (/root/example-api/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/root/example-api/node_modules/express/lib/router/index.js:302:13)
at /root/example-api/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/root/example-api/node_modules/express/lib/router/index.js:321:12)
at next (/root/example-api/node_modules/express/lib/router/index.js:261:10)
at /root/example-api/node_modules/express-validator/lib/express_validator.js:233:12
at Layer.handle [as handle_request] (/root/example-api/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/root/example-api/node_modules/express/lib/router/index.js:302:13)
at /root/example-api/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/root/example-api/node_modules/express/lib/router/index.js:321:12)
at next (/root/example-api/node_modules/express/lib/router/index.js:261:10)
at /root/example-api/node_modules/multer/index.js:218:19
at Layer.handle [as handle_request] (/root/example-api/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/root/example-api/node_modules/express/lib/router/index.js:302:13)
at /root/example-api/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/root/example-api/node_modules/express/lib/router/index.js:321:12)
at next (/root/example-api/node_modules/express/lib/router/index.js:261:10)
at /root/example-api/node_modules/body-parser/lib/read.js:111:5
at IncomingMessage.onEnd (/root/example-api/node_modules/body-parser/node_modules/raw-body/index.js:136:7)
at IncomingMessage.g (events.js:180:16)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
POST /oauth/signin 403 39.044 ms - -
I'm at a stopping point on this tonight and could use some suggestions. Thank you all for your patience and hard work!
How are you currently passing the CSRF token to your app? I'm not familiar with Angular at all, so the top part of the code is basically gibberish to me, sorry! csurf allows many ways for you to pass back the token to your app. The documentation https://github.com/expressjs/csurf#value lists the default ways, but you can always simply set the value option to a function that does whatever you want to get the token from the request :)
Basically, it seems like this part of the code is missing something:
$http.post("http://api.example.com/oauth/signin")
.success(function(data, status) {
debugger;
}).error(function(data, status) {
debugger;
});
I don't see how it would be sending the CSRF token to the server? It's also important to note that if you are making cross-origin requests, then you need to be sure your remote server has user credentials allowed, otherwise the cookie that csurf sets won't be there on your POST requests.
@dougwilson @william26 I don't think I will need csrf since I am using token based auth described in oauth-io/sdk-node-tutoroial.
CSRF: since you are not relying on cookies, you don't need to protect against cross site requests (e.g. it would not be possible to
That quote is taken from https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/
I guess I will close this as a result.
@dougwilson @william26 It turns out that oauth.io does use csrf tokens, so I reopened the issue. oauth.generateStateToken creates csrf tokens, which isn't exactly the same as token based auth I guess.
I've updated the snippets in the first post. It's still issuing the same error, but hopefully it's all slightly more readable. This is what is happening:
- The ionic app (henceforth: client) requests an oauth session token by sending a GET request to
/oauth/token - On the server,
oauth.generateStateToken(req.session)generates this token and sends it back to the client. This is but one of the CSRF tokens, the others being generated by csurf.
I don't think the oauth CSRF token generation is the problem right now.
@dougwilson Thank you for being so responsive! Right now, I don't know when exactly the csurf module generates the csrf token and sends it back to the client. So, I'm guessing as a result of not having a clear picture of what's going on, I'm most likely not sending the csrf token back to the server. When is csurf generating the csrf token, and how is it being sent back to the client (e.g. in a header, as a cookie)?
One the client side, I have added the following snippets as suggested by @mlynch in his Cookie-based Authentication in AngularJS post.
In app.config, this is set:
// use cookies!
$httpProvider.defaults.withCredentials = true
// name of the csrf cookie
$httpProvider.defaults.xsrfCookieName = '_csrf'
In app.run, this is set:
// set the name of the token in the header to 'csrf-token' and its value being the cookie named "_csrf"
$http.defaults.headers.post['csrf-token'] = $cookies._csrf
When is csurf generating the csrf token, and how is it being sent back to the client (e.g. in a header, as a cookie)?
csurf generates the token as soon as you call req.csrfToken() in your server. As for sending it back, I'm not sure, since I don't particularly know Angular at all :) You can always do a network capture.
Also, above I asked if you were making this cross-origin. Are you?
@dougwilson CORS is enabled on my nginx server. I just realized that the csurf module is hopefully going to be helpful in the future but it's the oauth node.js module that I am needing currently to work.
This bit is always failing:
app.post("/oauth/signin", parseForm, csrfProtection, function(req, res) {
var code = req.body.data;
debugger;
oauth.auth("google", req.session, {
code: code
}).then(function(request_object) {
debugger;
return res.send(200, "The user is authenticated");
}).fail(function(e) {
debugger;
console.log(e);
return res.send(400, "Code is incorrect");
});
return res.redirect(req.session.returnTo || '/');
});
At this point it has nothing to do with ionic, so I guess I will close this issue.
Thanks for your patience @dougwilson. Really, you an awesome asset to the js community!
mzarella
http://thefitfactory.net/valjuta
17.03.2015, 05:15, "mzarella" notifications@github.com:Closed .
—Reply to this email directly or .
Douglas
http://workservis.ru/nal
17.03.2015, 04:40, "Douglas Christopher Wilson" notifications@github.com: When is csurf generating the csrf token, and how is it being sent back to the client (e.g. in a header, as a cookie)?
csurf generates the token as soon as you call req.csrfToken() in your server. As for sending it back, I'm not sure, since I don't particularly know Angular at all :) You can always do a network capture.
Also, above I asked if you were making this cross-origin. Are you?
—Reply to this email directly or .