ionic-framework icon indicating copy to clipboard operation
ionic-framework copied to clipboard

docs: How to send CSRF information to the server?

Open mzarella opened this issue 11 years ago • 7 comments

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!

mzarella avatar Mar 16 '15 02:03 mzarella

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

dougwilson avatar Mar 16 '15 03:03 dougwilson

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 avatar Mar 16 '15 03:03 dougwilson

@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