0

I have a test webforms app downloaded from MS to connect to Azure Ad. It works running in Visual Studio with localhost and IIS express. But when I move it to the server it fails to connect. I have tried multiple things in the authority (tenant id, company) It gets the below stack trace.

[TaskCanceledException: A task was canceled.] System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +14354825 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60 Microsoft.IdentityModel.Protocols.d__8.MoveNext() +501

[IOException: IDX20804: Unable to retrieve document from: 'https://login.microsoftonline.com/Mytenantid/v2.0/.well-known/openid-configuration'.] Microsoft.IdentityModel.Protocols.d__8.MoveNext() +1372 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60 Microsoft.IdentityModel.Protocols.OpenIdConnect.d__3.MoveNext() +379 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60 Microsoft.IdentityModel.Protocols.d__24.MoveNext() +848

[InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://login.microsoftonline.com/Mytenantid/v2.0/.well-known/openid-configuration'.] Microsoft.IdentityModel.Protocols.d__24.MoveNext() +1562 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60 Microsoft.Owin.Security.OpenIdConnect.d__8.MoveNext() +547 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60 Microsoft.Owin.Security.Infrastructure.d__40.MoveNext() +349 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31

I have an older version of connecting in the same IIS instance with older packages that works.

URI https://Myserver/TestNewAccess

    
        // Authority is the URL for authority, composed by Microsoft identity platform endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
        string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["ida:AADInstance"], domain);


        public void ConfigureAuth(IAppBuilder app)
        {
            IdentityModelEventSource.ShowPII = true;

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = authority,
                    //PostLogoutRedirectUri = postLogoutRedirectUri,
                    RedirectUri = redirectUri,
                    Scope = OpenIdConnectScope.OpenId,
                    // ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                    ResponseType = OpenIdConnectResponseType.CodeIdToken,
                    
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        NameClaimType = "preferred_username",
                        ValidateIssuer = true // Simplification (see note below)
                    },
                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        AuthenticationFailed = (context) =>
                        {
                            return System.Threading.Tasks.Task.FromResult(0);
                        }
                    }

                }
                );

Portion of the web.config.

  <location path="Account">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  <system.web>
    <customErrors mode="Off"/>
    <authorization>
      <deny users="?" />
    </authorization>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>
  • If my reply is helpful, please accept it as answer(click on the mark option beside the reply to toggle it from greyed out to fill in.), see https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Jason Pan Mar 25 '21 at 04:37
  • I found the issue looking at an old version that was working. I had to add a default proxy to the web config. – pasteven Apr 02 '21 at 17:36

1 Answers1

0

I follow the steps to create webforms project with aad auth.

You can download my sample code, it works for me.

1 .web.config

<configuration>
  <appSettings>
    <add key="ida:ClientId" value="clientid" />
    <add key="ida:RedirectUri" value="https://yourapp.azurewebsites.net/" />
    <add key="ida:Tenant" value="Tenantid" />
    <add key="ida:Authority" value="https://login.microsoftonline.com/{Tenant ID}/v2.0" />
  </appSettings>
  <location path="Account">
    <system.web>
      <customErrors mode="Off"/>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  <system.web>
    <authorization>
      <deny users="?" />
    </authorization>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
  </system.web>
  <system.webServer>
  1. StartupAuth.cs

     public void ConfigureAuth(IAppBuilder app)
         {
             IdentityModelEventSource.ShowPII = true;
    
             app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
    
             app.UseCookieAuthentication(new CookieAuthenticationOptions { });
    
             // instead of using the default validation (validating against a single issuer value, as we do in line of business apps), 
             // we inject our own multitenant validation logic
             app.UseOpenIdConnectAuthentication(
                 new OpenIdConnectAuthenticationOptions
                 {
                     // Sets the ClientId, authority, RedirectUri as obtained from web.config
                     ClientId = clientId,
                     Authority = authority,
                     RedirectUri = redirectUri,
                     // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                     PostLogoutRedirectUri = redirectUri,
                     Scope = OpenIdConnectScope.OpenIdProfile,
                     // ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                     ResponseType = OpenIdConnectResponseType.CodeIdToken,
    
                     TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                     {
                         NameClaimType = "preferred_username",
                         ValidateIssuer = true // Simplification (see note below)
                     },
                     Notifications = new OpenIdConnectAuthenticationNotifications()
                     {   
                         SecurityTokenValidated = (context) =>
                         {
                             // If your authentication logic is based on users
                             return Task.FromResult(0);
                         },
                         AuthenticationFailed = (context) =>
                         {
                             // Pass in the context back to the app
                             context.HandleResponse();
                             // Suppress the exception
                             return Task.FromResult(0);
                         }
                     }
                 });
    
             // This makes any middleware defined above this line run before the Authorization rule is applied in web.config
             app.UseStageMarker(PipelineStage.Authenticate);
         }
    
  2. App registrations

    enter image description here

The specific cause of your problem has something to do with the project itself. For further Troubleshoot, you can follow the post below to find the log and troubleshoot the problem.

Azure - Unhandled Exception: System.IO.FileNotFoundException

enter image description here

Test Result

enter image description here

Jason Pan
  • 15,263
  • 1
  • 14
  • 29
  • No luck so far. I am not sure if the error is in the IIS setup or the Azure setup. – pasteven Mar 25 '21 at 17:59
  • @pasteven Recreate a test webapp, add new app registration , follow my steps to test. – Jason Pan Mar 26 '21 at 02:39
  • @pasteven I think you should troubleshoot, it will improve your ability to solve problems. You can update the error logs which you can find in `Application Event Logs` in the post later. – Jason Pan Mar 26 '21 at 02:42