Posts by Robbert van Waveren

Stateless Spring Security Part 3: JWT + Social Authentication

Posted on by  
Robbert van Waveren

This third and final part in my Stateless Spring Security series is about mixing previous post about JWT token based authentication with spring-social-security. This post directly builds upon it and focusses mostly on the changed parts. The idea is to substitude the username/password based login with "Login with Facebook" functionality based on OAuth 2, but still use the same token based authentication after that.

The user clicks on the "Login with Facebook" button which is a simple link to "/auth/facebook", the SocialAuthenticationFilter notices the lack of additional query parameters and triggers a redirect leading the user of your site to Facebook. They login with their username/password and are redirected back, again to "/auth/facebook" but this time with "?code=...&state=..." parameters specified. (If the user previously logged in at facebook and had a cookie set, facebook will even instantly redirect back and no facebook screen is shown at all to the user.) The fun part is that you can follow this in a browsers network log as it's all done using plain HTTP 302 redirects. (The "Location" header in the HTTP response is used to tell the browser where to go next)

Continue reading →

Stateless Spring Security Part 2: Stateless Authentication

Posted on by  
Robbert van Waveren

This second part of the Stateless Spring Security series is about exploring means of authentication in a stateless way. If you missed the first part about CSRF you can find it here. So when talking about Authentication, its all about having the client identify itself to the server in a verifiable manner. Typically this start with the server providing the client with a challenge, like a request to fill in a username / password. Today I want to focus on what happens after passing such initial (manual) challenge and how to deal with automatic re-authentication of futher HTTP requests.

The most common approach we probably all know is to use a server generated secret token (Session key) in the form of a JSESSIONID cookie. Initial setup for this is near nothing these days perhaps making you forget you have a choice to make here in the first place. Even without further using this "Session key" to store any other state "in the session", the key itself is in fact state as well.  I.e. without a shared and persistent storage of these keys, no successful authentication will survive a server reboot or requests being load balanced to another server.

Continue reading →

Stateless Spring Security Part 1: Stateless CSRF protection

Posted on by  
Robbert van Waveren

Today with a RESTful architecture becoming more and more standard it might be worthwhile to spend some time rethinking your current security approaches. Within this small series of blog posts we'll explore a few relatively new ways of solving web related security issues in a Stateless way. This first entry is about protecting your website against Cross-Site Request Forgery (CSRF).

CSRF attacks are based on lingering authentication cookies. After being logged in or otherwise identified as a unique visitor on a site, that site is likely to leave a cookie within the browser. Without explicitly logging out or otherwise removing this cookie, it is likely to remain valid for some time. Another site can abuse this by having the browser make (Cross-Site) requests to the site under attack. For example including some Javascript to make a POST to "http://siteunderattack.com/changepassword?pw=hacked" will have the browser make that request, attaching any (authentication) cookies still active for that domain to the request! Even though the Single-Origin Policy (SOP) does not allow the malicious site read access to any part of the response. As probably clear from the example above, the harm is already be done if the requested URL triggers any side-effects (state changes) in the background.

Continue reading →

An exploration on locking and atomicity in Redis

Posted on by  
Robbert van Waveren

Lately I've been doing some development of a turn based browser game using node.js and Redis. Being intended to run on multiple node.js instances and each instance also being able to "autoplay" for afk users, it was clearly lacking a semaphore of some sort to make sure only one action at the time would be processed per game across all nodes. With Redis being my central persistence component I figured this was a good time to dive a bit deeper in the capabilities of Redis when it comes to locking. As it turns out locking makes a great use-case to learn about the true power of some of the most basic Redis commands. So while this blog post is definitely about locking with Redis, its actually more about how common Redis commands can be used to solve some pretty complex issues. Generally locking patterns can be divided into pessimistic and optimistic. In this blog I'm focusing on the creation of a general purpose (pessimistic) lock/semaphore that could be used for anything that requires limiting access to a resource or piece of code really. The third example also uses the build-in optimistic locking capabilities of Redis to solve to a race condition issue. Keep in mind though, that in either case it is the client that is responsible for maintaining the relation between "the lock" and "the resource". Lets start with the oldest and most common locking pattern and work our way through from there.   1. SETNX/GETSET based locking The commands of choice for the first example (works on all Redis versions): SETNX only sets a key to a value if it does Not eXists yet. GETSET gets an old value and sets it to a new value atomically!

var redis = require('redis');
var nameOfKeyToLock = 'the_lock';
var timeout = 10000;
var retry_time = 500;

var doLocked = function(client, nameOfKeyToLock, callback){
  var lock = function() {

    var newLockValue = Date.now() + timeout;

    //SETNX command
    client.setnx(nameOfKeyToLock, newLockValue, function(err, result){
      if(result === 0){
        client.get(nameOfKeyToLock, function(err, currentValue){
          currentValue = parseFloat(currentValue);
          if(currentValue > Date.now()){
            //lock still valid, retry later
            return retry();
          }

          newLockValue = Date.now() + timeout;
          //GETSET command
          client.getset(nameOfKeyToLock, newLockValue, function(err, check){
            if(currentValue == check){
              //old value was still the same, so now the lock is ours
              return callback(unlock);
            }
            retry();
          });
        });
      } else {
        //no lock was present, we now got it
        callback(unlock);
      }
    });

    var unlock = function(after){
      if(newLockValue > Date.now()){
        client.del(nameOfKeyToLock, function(){
          console.log('released lock');
          after();
        });
      } else {
        after();
      }
    };
  };
  var retry = function() {
    console.log('scheduling retry');
    setTimeout(lock, retry_time);
  }
  lock();
};

Continue reading →

shadow-left