Error: Unable to retrieve document from: 'https://login.microsoftonline.com/.well-known/openid-configuration'

Marlo E. Hutchinson 31 Reputation points
2022-07-11T22:05:35.893+00:00

ASP.NET MVC 4.8
Azure SQL Server
Azure Tenant
App Registration

  • Authentication configured for redirecturi

Please let me what else I can provide.

I have been able to deploy this application to an azure "dev" and "test" environment. However, under a prod (premium) PLAN environment, I have been unsuccessful. I am unable to use the configuration web.config and application registration / authentication use for DEV and TEST. I reverted back to an older working configuration (for prod only) (different tenant), and still does not work.

I have not been able to find any help/clues in stack overflow. I just understand it's related to authentication.

WEB.CONFIG
<!-- Azure Active Directory Authentication Settings -->
<add key="ida:AADInstance" value="https://login.microsoftonline.com/" />
<add key="clientSecret" value="PvO8Q~********" />
<add key="ida:ClientId" value="*****" />
<add key="ida:Domain" value="valorhealthcare.onmicrosoft.com" />
<add key="ida:TenantId" value="ba*****" />
<add key="ida:RedirectUri" value="https://s*****-prod1.azurewebsites.net/.auth/login/aad/callback" />
<add key="ida:PostLogoutRedirectUri" value="https://localhost:44341/" />

STARTUP.AUTH.CS
public partial class Startup
{
private static readonly string ClientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static readonly string ClientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
private static readonly string RedirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
private static readonly string GraphScopes = ConfigurationManager.AppSettings["ida:AppScopes"];
private static readonly string AADInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static readonly string TenantId = ConfigurationManager.AppSettings["ida:TenantId"];
private static readonly string Authority = string.Format(CultureInfo.InvariantCulture, AADInstance, "common", "/v2.0");

    /// <summary>  
    ///   
    /// </summary>  
    /// <param name="app"></param>  
    public void ConfigureAuth(IAppBuilder app)  
    {  
        IdentityModelEventSource.ShowPII = true;  
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);  

        app.UseCookieAuthentication(new CookieAuthenticationOptions());  

        app.UseOAuth2CodeRedeemer(  
            new OAuth2CodeRedeemerOptions  
            {  
                ClientId = ClientId,  
                ClientSecret = ClientSecret,  
                RedirectUri = RedirectUri  
            });  

        app.UseOpenIdConnectAuthentication(  
            new OpenIdConnectAuthenticationOptions  
            {  
                Authority = Authority,  
                ClientId = ClientId,  
                RedirectUri = RedirectUri,  
                PostLogoutRedirectUri = RedirectUri,  
                Scope = "openid email profile offline_access" + GraphScopes,  
                TokenValidationParameters = new TokenValidationParameters  
                {  
                    // For demo purposes only, see below  
                    ValidateIssuer = false  

                    // In a real application you would use IssuerValidator for additional checks, like making sure the user's organization has signed up for your app.  
                    //     IssuerValidator = (issuer, token, tvp) =>  
                    //     {  
                    //        //if(MyCustomTenantValidation(issuer))  
                    //        return issuer;  
                    //        //else  
                    //        //    throw new SecurityTokenInvalidIssuerException("Invalid issuer");  
                    //    },  
                    //NameClaimType = "name",  
                },  
                Notifications = new OpenIdConnectAuthenticationNotifications  
                {  
                    AuthenticationFailed = OnAuthenticationFailedAsync,  
                    AuthorizationCodeReceived = OnAuthorizationCodeReceivedAsync  
                },  
                // Handling SameSite cookie according to https://learn.microsoft.com/en-us/aspnet/samesite/owin-samesite  
                CookieManager = new SameSiteCookieManager(  
                    new SystemWebCookieManager())  
            }  
        );  
    }  

    private static Task OnAuthenticationFailedAsync(AuthenticationFailedNotification<OpenIdConnectMessage,  
      OpenIdConnectAuthenticationOptions> notification)  
    {  
        notification.HandleResponse();  
        notification.Response.Redirect("/Error?message=" + notification.Exception.Message);  
        return Task.FromResult(0);  
    }  

    private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification context)  
    {  
        IConfidentialClientApplication idClient = ConfidentialClientApplicationBuilder.Create(ClientId)  
            .WithClientSecret(ClientSecret)  
            .WithRedirectUri(RedirectUri)  
            .WithAuthority(new Uri(Authority))  
            .Build();  
        AuthenticationResult result = await idClient.AcquireTokenByAuthorizationCode(new[] { "User.Read" }, context.Code).ExecuteAsync();  
    }  

}  

WEB PAGE STACKTRACE
Server Error in '/' Application.
IDX20807: Unable to retrieve document from: 'https://login.microsoftonline.com/.well-known/openid-configuration'. HttpResponseMessage: 'StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
x-ms-request-id: a02f9ab3-8f71-46bd-aa7a-8dcfbc710700
x-ms-ests-server: 2.1.13156.10 - SCUS ProdSlices
X-XSS-Protection: 0
Cache-Control: private
Date: Mon, 11 Jul 2022 21:32:59 GMT
P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
Set-Cookie: x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly
Content-Length: 0
}', HttpResponseMessage.Content: ''.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.IOException: IDX20807: Unable to retrieve document from: 'https://login.microsoftonline.com/.well-known/openid-configuration'. HttpResponseMessage: 'StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
x-ms-request-id: a02f9ab3-8f71-46bd-aa7a-8dcfbc710700
x-ms-ests-server: 2.1.13156.10 - SCUS ProdSlices
X-XSS-Protection: 0
Cache-Control: private
Date: Mon, 11 Jul 2022 21:32:59 GMT
P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
Set-Cookie: x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly
Content-Length: 0
}', HttpResponseMessage.Content: ''.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[IOException: IDX20807: Unable to retrieve document from: 'https://login.microsoftonline.com/.well-known/openid-configuration'. HttpResponseMessage: 'StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
x-ms-request-id: a02f9ab3-8f71-46bd-aa7a-8dcfbc710700
x-ms-ests-server: 2.1.13156.10 - SCUS ProdSlices
X-XSS-Protection: 0
Cache-Control: private
Date: Mon, 11 Jul 2022 21:32:59 GMT
P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
Set-Cookie: x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly
Content-Length: 0
}', HttpResponseMessage.Content: ''.]
Microsoft.IdentityModel.Protocols.<GetDocumentAsync>d__22.MoveNext() +890
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.IdentityModel.Protocols.OpenIdConnect.<GetAsync>d__3.MoveNext() +291
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +26
Microsoft.IdentityModel.Protocols.<GetConfigurationAsync>d__14.MoveNext() +752

[InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://login.microsoftonline.com/.well-known/openid-configuration'.]
Microsoft.IdentityModel.Protocols.<GetConfigurationAsync>d__14.MoveNext() +1389
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.Owin.Security.OpenIdConnect.<ApplyResponseChallengeAsync>d__10.MoveNext() +489
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.Owin.Security.Infrastructure.<ApplyResponseCoreAsync>d__40.MoveNext() +272
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.Owin.Security.Infrastructure.<ApplyResponseAsync>d__39.MoveNext() +271
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.Owin.Security.Infrastructure.<TeardownAsync>d__34.MoveNext() +158
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.Owin.Security.Infrastructure.<Invoke>d__5.MoveNext() +661
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
SaveRecapture.Utils.<Invoke>d__2.MoveNext() in C:\Users\mhutchinson\source\repos\SaveRecapture\SaveRecapture\Utils\OAuth2CodeRedeemerMiddleware.cs:101
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__7.MoveNext() +179
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.Owin.Security.Infrastructure.<Invoke>d__5.MoveNext() +521
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__7.MoveNext() +179
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<DoFinalWork>d__12.MoveNext() +180
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +69
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +64
System.Web.AsyncEventExecutionStep.InvokeEndHandler(IAsyncResult ar) +156
System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) +123

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.8.4494.0

Microsoft Security Microsoft Entra Microsoft Entra ID
{count} votes

Accepted answer
  1. Shweta Mathur 30,296 Reputation points Microsoft Employee Moderator
    2022-07-18T12:14:35.167+00:00

    Hi @Anonymous ,

    As we have came across different scenarios or issues while troubleshooting the error: IDX20807: Unable to retrieve document from: 'https://login.microsoftonline.com/.well-known/openid-configuration .I am summarizing all the issues here to troubleshoot such errors for better understanding to help others in the community.

    Issue 1: Exception Details: System.IO.IOException: IDX20807: Unable to retrieve document from: 'https://login.microsoftonline.com/.well-known/openid-configuration'. HttpResponseMessage: 'StatusCode: 404, ReasonPhrase: 'Not Found',

    Solution: OIDC metadata resulting in this case is https://login.microsoftonline.com/.well-known/openid-configuration is not valid due to web configuration has not been correctly configured in the application. In this case, it seems the value configured in authority parameter is not recognized properly.

    So, updated the authority parameter with below configuration help to resolve incorrect OIDC metadata issue which was missing the tenant (common) and version (v2.0) initially.

    <add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}{1}" />

    In Startup.Auth.cs

    public static string AADInstance { get; } = ConfigurationManager.AppSettings["ida:AADInstance"];
    public static string Authority = string.Format(CultureInfo.InvariantCulture, AADInstance, "common", "/v2.0");

    Issue 2: Page flickers while trying to Sign In the application.

    Solution: Endpoints configured in the application is not correct. For common endpoint, application should be registered as multi-tenant application for wider audience. If application is configured as single-tenant application, then tenant id should be passed in the endpoint in place of common.

    Here, as application is registered as single-tenant application, updating the endpoint from common to specific tenant-id resolve the Sign In issue.

    Issue 3: HttpResponseMessage.Content: '{"error":"invalid_request","error_description":"AADSTS1002016: You are using TLS version 1.0, 1.1 and/or 3DES cipher which are deprecated to improve the security posture of Azure AD. Your TenantID is: ba82623a-5cb6-404c-8b67-197a3a8840ad. Please refer to https://go.microsoft.com/fwlink/?linkid=2161187 and conduct needed actions to remediate the issue.

    Solution: This error is due to deprecated version of TLS in production environment. As TLS 1.0 ,1.1 got deprecated for Azure on January 31, 2022. So TLS need to upgrade to 1.2 to resolve this issue and authenticate using Azure AD.
    Reference: https://learn.microsoft.com/en-us/troubleshoot/azure/active-directory/enable-support-tls-environment?tabs=azure-monitor

    Hope this will help to clearly understand the issues encountered while troubleshooting the root issue.
    Please let us know if you require any further help.

    Thanks,
    Shweta

    ---------------------------

    Please do not forget to "Accept the answer" and provide the feedback wherever the information provided helps you to help others in the community.


1 additional answer

Sort by: Most helpful
  1. Shweta Mathur 30,296 Reputation points Microsoft Employee Moderator
    2022-07-13T16:00:09.243+00:00

    Hi @Anonymous ,

    Thanks for reaching out and apologies for delay in response.

    I understand that you are facing issue in Azure production and getting error "Unable to retrieve document from: 'https://login.microsoftonline.com/.well-known/openid-configuration'. "

    If you can see in error OIDC metadata resulting in your case is https://login.microsoftonline.com/.well-known/openid-configuration which is not valid, and application is not able to retrieve the information correctly.

    I am still trying to figure why it is not working in production environment only. You can try to debug and fetch OIDC metadata in other environments to get the flow. As per your configration it should be https://login.microsoftonline.com/**common/v2.0**/.well-known/openid-configuration'

    In this case, it seems the value configured in authority parameter is not recognized properly.

    Could you please try to update private static readonly string Authority = string.Format(CultureInfo.InvariantCulture, Configuration["AzureAd:AadInstance"], "common", "/v2.0").

    Hope this will help to understand the issue.

    Thanks,
    Shweta

    -------------------------------

    Please remember to "Accept Answer" if answer helped you.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.