Using Redis as a session state provider

2.9k views Asked by At

I am wanting to create real RESTful APIs with ASP.Net. According to REST architecture. The application must be stateless. Meaning I can't use normal sessions. I found a document here describing how to use Redis as a session state provider. Since it would be external (as in not part of the server), would it be suitable for creating stateless APIs? How would I go about it. Would I just create a key to declare the user as authenticated and then maybe a key to reference the current user, or am I thinking wrong?

1

There are 1 answers

3
Eli On BEST ANSWER

You could use Redis as a cache to hold various pieces of state about the user. The idea is that when the user logs in, you probably need to load a bunch of information about them from your database (name, address, etc...) at that point, you know the user will likely need to reuse some of that information, so you don't want to keep reloading it from the database each time. Instead you can cache it in Redis for a few minutes, so on the user's next request you can just pull the data very quickly from Redis instead of having to go back to your database.

For authentication, you could create a temporary token in the redis cache that you also throw back to the user as a cookie so that you can check for it's existence on subsequent requests instead of needing to run a bunch of time-consuming bcrypt hashes or some such for each subsequent authentication.

This all remains stateless because even if the cache is not available for whatever reason, the user's requests still contain all the state necessary to answer his or her requests. All that Redis is doing is allowing you to speed up your responses if it's available.