Getting intermittent no response from login.microsoftonline.com/common/v2.0

Viewed 28

We secure our API using Azure AD. Using Micorosft.IdentityModel.Protocol.Extensions. We have an issue that this API sometimes crash in Prod because it can't connect to the provider or can't get the configuration from https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration.

I also created an API to get the username based on the sign-in user but that endpoint sometimes doesn't respond. Is there a way to fix this issue?

public class EmployeeController : BaseController
{
    [Route("employee/sign-in-user/username")]
    [HttpGet]
    public IHttpActionResult GetEmployeeUsernameBasedOnSignInUser()
    {

        string email = "";
        var employeeRepository = new EmployeeRepository();

        var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
            email = userClaims?.FindFirst(System.Security.Claims.ClaimTypes.Upn)?.Value;

        var employeeUsername = employeeRepository.GetUsernameByEmail(email);
        return Ok(employeeUsername);
    }

}


public partial class Startup
{
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static bool enableSso = bool.Parse(ConfigurationManager.AppSettings["EnableSSO"]);

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                AccessTokenFormat = new JwtFormat(
              new TokenValidationParameters
              {
                  // Check if the audience is intended to be this application
                  ValidAudiences = new[] { clientId, $"api://{clientId}" },

                  // Change below to 'true' if you want this Web API to accept tokens issued to one Azure AD tenant only (single-tenant)
                  // Note that this is a simplification for the quickstart here. You should validate the issuer. For details, 
                  // see https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore
                  ValidateIssuer = false,
                  NameClaimType = "name"
                  //NameClaimType = "preferred_username"
                  //NameClaimType = "email"

              },
              new OpenIdConnectSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration")
          ),
            });
    }
}


public class OpenIdConnectSecurityTokenProvider : IIssuerSecurityTokenProvider
{
    public ConfigurationManager<OpenIdConnectConfiguration> ConfigManager;
    private string _issuer;
    private IEnumerable<SecurityToken> _tokens;
    private readonly string _metadataEndpoint;

    private readonly ReaderWriterLockSlim _synclock = new ReaderWriterLockSlim();

    public OpenIdConnectSecurityTokenProvider(string metadataEndpoint)
    {
        _metadataEndpoint = metadataEndpoint;
        ConfigManager = new ConfigurationManager<OpenIdConnectConfiguration>(metadataEndpoint);

        RetrieveMetadata();
    }

    /// <summary>
    /// Gets the issuer the credentials are for.
    /// </summary>
    /// <value>
    /// The issuer the credentials are for.
    /// </value>
    public string Issuer
    {
        get
        {
            RetrieveMetadata();
            _synclock.EnterReadLock();
            try
            {
                return _issuer;
            }
            finally
            {
                _synclock.ExitReadLock();
            }
        }
    }

    /// <summary>
    /// Gets all known security tokens.
    /// </summary>
    /// <value>
    /// All known security tokens.
    /// </value>
    public IEnumerable<SecurityToken> SecurityTokens
    {
        get
        {
            RetrieveMetadata();
            _synclock.EnterReadLock();
            try
            {
                return _tokens;
            }
            finally
            {
                _synclock.ExitReadLock();
            }
        }
    }

    private void RetrieveMetadata()
    {
        _synclock.EnterWriteLock();
        try
        {
            OpenIdConnectConfiguration config = ConfigManager.GetConfigurationAsync().Result;
            _issuer = config.Issuer;
            _tokens = config.SigningTokens;
        }
        finally
        {
            _synclock.ExitWriteLock();
        }
    }
}
0 Answers
Related