Working on the server side of a java based web application (will serve mobile and web clients) and I need to implement users authentication. In production I have 2 servers (duplicated, working against the same DB) with a load balancer. I used Spring security before so this is the most intuitive way for me but here is my issue:
Spring security authenticates the user once against the DB (when the user logs-in) and later requests are processed and authenticated using a session based token. Now, suppose that one of my production servers is down then I’m loosing my session, meaning the user will get some sort of “unauthorized” response. How can I deal with this?
I thought of 3 options
- Use a key-value store such as redis and save my tokens there. If I do that I guess I have to interfere with springs core code – once when user logges in (save the token to the key-value store) and once when authenticating a user (authenticate against this key-value store instead of spring’s in-memory HttpSessionSecurityContextRepository).
- Use Spring security in a way that it authenticates users against the DB in every request (I’m not sure it is even possible).
- Not using spring security and simply create a filter or some interceptor in order to authenticate each and every request against the DB. This means 2 things: the firsts is that my client will have to apply username and password to each and every request (probably in the header), And second is that I will have to query the DB for each and every request.
So these are my thoughts, I would like to get your insights about those and new suggestions if you have.
How about the state the user maintains across the session?
If you have such a situation, than you’ll lose the data if the server fails.
I think the best would be starting with sticky session mechanism here and leaving the authentication as is.
Sticky session can be configured on the load balancer and usually means the following:
- Once the use from IP A opens your aplication on server S1 all the subsequent requests will be redirected to this server, but the next user will be automatically connected to server S2 (load balancer will make such a decision). So all-in-all, if you have, say, 10 users working at the same time, 5 of them will be connected to server S1 and the rest to the server B.
I don’t think that authenticating each request is a good idea (think about web 2, ajax requests) – this will make your server and db highly loaded and as a result it won’t be able to process a lot of users/requests simultaneously.
Hope this helps