[SOLVED] Where to store Access and Refresh tokens


I’m making an OAuth2 call from my ASP.NET MVC web application to my Web API through JavaScript to authenticate my user and get a token. The Web API accesses a SQL Server database where the user’s login is stored using Identity and the typical AspNetUsers tables. My API call returns a 20 min access token and a 2 week refresh token. The API and consuming apps are products that we are developing that our customers will register with. In other words, all the code is on our side.

I know I must refresh the access token before it expires by passing the API the refresh token. My question is…where do I store the access and refresh tokens on the client for use in my JavaScript to make subsequent API calls or to refresh the token? People online are saying that storing anything client-side is bad, cookies are unsecure, etc and without offering any solutions. Local storage? But of course these are Ajax calls in JavaScript that we are making to the API, so the tokens needs to exist somewhere on the client side! It’s driving me crazy trying to figure this out. I know I need to at least use HTTPS.


I’d suggest you to create a table in database to store the refresh token and access token.
Table structure will look like below


Whenever you’re calling a API with access token , please check the current time and LastUpdated_Time of token , if it is more than one hour your token will become invalid, so you need to get another valid token using your refresh token.
In my application , I had 55 minutes lifespan of toke, after that time token gets invalid.


if (dateTimeDiff > 55) {
    var request = (HttpWebRequest) WebRequest.Create("https://www.googleapis.com/oauth2/v3/token");
    var postData = "refresh_token=your refresh token";
    postData += "&client_id=your client id";
    postData += "&client_secret=your client secret";
    postData += "&grant_type=refresh_token";

    var data = Encoding.ASCII.GetBytes(postData);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;
    request.UseDefaultCredentials = true;

    using(var stream = request.GetRequestStream()) {
        stream.Write(data, 0, data.Length);
    var response = (HttpWebResponse) request.GetResponse();
    string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();


The response will contain new access token, don’t forget to update your table with LastUpdated_Time and new token.

Answered By – AhammadaliPK

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *