Search code examples
asp.net-coreweb-applicationsazure-active-directoryopenid-connect

OPEN ID connect request to refresh access token


I'm implementing Azure Ad with Open ID connect for my web app. Intermittently, I get an expired token after logging in which causes the life time validation to fail. I think what I need is to request a refresh access token with new life time.

Here is what I have so far, on how to request it, but no luck. I have tried different end points as well, but not quite sure which on is correct. Some endpoints requires GET method not POST.

            var accessToken = await HttpContext.GetTokenAsync("access_token");
            var tokenEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
            //tokenEndpoint = "https://login.microsoftonline.com/{myClientID}/v2.0";
            var clientId = "myClientID";
            var clientSecret = "mySecret";
            var refreshToken = await HttpContext.GetTokenAsync("refresh_token");
            
            var requestData = new[]
            {
                new KeyValuePair<string, string>("client_id", clientId),
                new KeyValuePair<string, string>("client_secret", clientSecret),
                new KeyValuePair<string, string>("grant_type", "refresh_token"),
                new KeyValuePair<string, string>("refresh_token", refreshToken),
            };

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                var response = await client.PostAsync(tokenEndpoint, new FormUrlEncodedContent(requestData));

                response.EnsureSuccessStatusCode();

                var json = await response.Content.ReadAsStringAsync();

            }

If this is not the correct way to requesting, what is the correct way?


Solution

  • Please look at the following answers to see if it helps you:

    Also, this Microsoft document provides details and examples:

    You should not have to make separate calls to get access and refresh tokens, in each case you should get back both in the HTTP response body.

    Also, it looks like certain versions of DotNet core have a bug: