Search code examples
asp.net-mvccookiesasp.net-mvc-5oauth-2.0asp.net-identity

OAuth2 refresh token in cookie


We are creating an Asp.NET MVC-5 application with Identity, and the database is accessed through a WebAPI using OAuth2. When a user logs in with a username and password, the MVC application uses this info to log in to the WebAPI to request the first access_token and refresh_token. These tokens are stored in the MVC application in a dictionary with the user's username as the key. The tokens are not exposed outside of the MVC Application. We then use the user's username to retrieve the tokens from the dictionary each request that the user makes.

We use Identity with Cookie Authentication in the MVC Application. The MVC Application is going to restart every once in a while (every week or so), which means we'll lose the access and refresh tokens stored in memory.

My questions:

  1. We use the UserName provided by User.Identity.Name as the key to retrieve the user's access_token and refresh_token from the dictionary. Is this safe? I assume Identity retrieves this from the cookie. Would it be possible for a user to change the cookie to pretend to be another user, or is Identity's serialization safe enough?

  2. I plan to store the refresh token in the cookie as well, so that when the MVC application has restarted, we can use this token to authenticate the user without forcing the user to log back in. This is basically the same question as 1. Is this safe?

  3. If both are in fact not safe, would it be sufficient to create a small local database where we store this data, and use a GUID in the cookie to retrieve it? We're trying to avoid needing a local database, but if it's necessary then so be it.

Thanks for the help.


Solution

  • It's not secure to store the refresh or access tokens in cookies.

    Please refer to Where to store access and refresh tokens on ASP.NET client web app - calling a REST API

    You shouldn't be concerned about "losing the access and refresh tokens stored in memory". If it happens, just recreate them.

    BTW: Storing any user data at in-memory dictionary is not a good idea. Use ASP Session management. It would be much easier to add any backed to that (in-proc, database, redis).