1

I have a .Net Web API secured with Azure AD and through C# console application I need to generate a token and call the API.

I am using the old ADAL.NET approach as it's a legacy app and supports V1.0 AD endpoints.

The below code works, but for every call, a NEW token is generated with a NEW expiry date/time.

How to cache it till it expiry and automatically silently renew it?

I tried the below code, but seems it's not working.

private async Task<string> GetTokenAsync()
    {
        // Create the AuthenticationContext with token cache
        var authContext = new AuthenticationContext("https://login.windows.net/{tenant_id}", new TokenCache());
        var credential = new ClientCredential("ClientID", "ClientSecret");

        try
        {
            // Acquire an access token for the API
            var result = await authContext.AcquireTokenAsync("Resource", credential);
            return result.AccessToken;
        }
        catch (AdalSilentTokenAcquisitionException)
        {
            // If AcquireTokenAsync fails, try refreshing the token using AcquireTokenSilentAsync
            try
            {
                var result = await authContext.AcquireTokenSilentAsync("Resource", credential, UserIdentifier.AnyUser);
                return result.AccessToken;
            }
            catch (AdalException exception)
            {
            }
        }
        catch (AdalException exception)
        {
        }
        catch (Exception exception)
        {
        }

        return string.Empty;
    }
user584018
  • 10,186
  • 15
  • 74
  • 160

1 Answers1

1

a. Lets assume the token expiry set to 1 min. What if user access the endpoints after 1 min. The user will not able to access the end point only (UnAtuthorize error will be thrown). Handling token expiration (silently) code on server side will never get called.

b. I would suggest to include token expiration at part of response. And store the Refreshtoken and expiration details on the client side (can be stored on 'httpOnly cookie' if client is web app).

    public class Token
    {
        public string AccessToken { get; set; }
        public string RefreshToken { get; set; }
        public DateTime TokenValidity { get; set; } 
    }
private async Task<Token> GetTokenAsync()
    {
        ....
        ...
        return new Token { AccessToken = "xxxxx"   RefreshToken = "xxxxx", TokenValidity= "xxxx" };
    }

c. Condition can be put on client side code to check if the token is expired or not and then call RefreshToken endpoint. Similar question is discussed on the thread

d. Or other way is, simply call endpoint. if the endpoint returns the UnAuthorized error, call RefreshToken endpoint with RefreshToken and TokenValidity data.

Abhishek Vyas
  • 599
  • 1
  • 9
  • 24