Philip Bergström Philip Bergström - 1 year ago 222
ASP.NET (C#) Question

Handling JWT expiration in .NET MVC-application

I have an ASP.NET MVC-application which is storing a JWT-token and a refresh token from my Web API in Session. My question is what to do when the JWT-token expires and it is time to refresh it. As I see it my two options are:

  1. Try to make a request to the Web API using the JWT-token and if it returns 401 Unauthorized, try refreshing the JWT-token.

  2. Using a timer to automatically refresh the JWT-token before it expires.

What are advantages of using either of these two methods, and how can I programatically implement them in an easy way? For example, do I have to use a try and catch for every call to the API if i use option 1?

Answer Source

I decided to go with option 2 in order to minimize the number of calls to the API. I then created a base controller class with a HttpClient factory method, which also checks if the JWT is about to expire:

        public HttpClient GetHttpClient(string baseAdress)
            var client = new HttpClient();
            client.BaseAddress = new Uri(baseAdress);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            string token;
            if (Session["access_token"] != null)
                var jwthandler = new JwtSecurityTokenHandler();
                var jwttoken = jwthandler.ReadToken(Session["access_token"] as string);
                var expDate = jwttoken.ValidTo;
                if (expDate < DateTime.UtcNow.AddMinutes(1))
                    token = GetAccessToken().Result;
                    token = Session["access_token"] as string;
                token = GetAccessToken().Result;

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            Session["access_token"] = token;
            return client;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download