ERROR Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer

Viewed 53

I have recently migrated the asp.net core mvc application from 3.1 to 6.0. The deployment works well on localhost, sandbox and Development environment. However, up on migration to QA environment throws few issues. I pulled up the log file and below is the error. The previous version 3.1 had been working with oauth2 but after migration to 6, it is throwing 500 error. Is this a certificate issue that I need to register with DNS? I am unable to hit "https://login-qa.aa.aaa/oauth2/default/.well-known/openid-configuration" from QA Server browser but 3.1 net core solution with the same openid configuration works well with no issues. Please assist.

2022-09-14 11:00:26,986 [.NET ThreadPool Worker] INFO  Microsoft.AspNetCore.Hosting.Diagnostics [(null)] - Request starting HTTP/1.1 GET http://portqa-hh.webapp.aa.aaa/ - -
2022-09-14 11:00:27,050 [.NET ThreadPool Worker] INFO  Microsoft.AspNetCore.Routing.EndpointMiddleware [(null)] - Executing endpoint 'App.Web.Controllers.HomeController.Index (App.Web)'
2022-09-14 11:00:27,068 [.NET ThreadPool Worker] INFO  Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker [(null)] - Route matched with {action = "Index", controller = "Home"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Index() on controller App.Web.Controllers.HomeController (App.Web).
2022-09-14 11:00:27,073 [.NET ThreadPool Worker] INFO  Microsoft.AspNetCore.Authorization.DefaultAuthorizationService [(null)] - Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
2022-09-14 11:00:27,074 [.NET ThreadPool Worker] INFO  Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker [(null)] - Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
2022-09-14 11:00:27,075 [.NET ThreadPool Worker] INFO  Microsoft.AspNetCore.Mvc.ChallengeResult [(null)] - Executing ChallengeResult with authentication schemes ().
2022-09-14 11:00:30,188 [.NET ThreadPool Worker] INFO  Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker [(null)] - Executed action App.Web.Controllers.HomeController.Index (App.Web) in 3113.9495ms
2022-09-14 11:00:30,188 [.NET ThreadPool Worker] INFO  Microsoft.AspNetCore.Routing.EndpointMiddleware [(null)] - Executed endpoint 'App.Web.Controllers.HomeController.Index (App.Web)'
2022-09-14 11:00:30,216 [.NET ThreadPool Worker] ERROR Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer [(null)] - Connection ID "17870283331606675461", Request ID "80000006-0002-f800-b63f-84710c7967bb": An unhandled exception was thrown by the application.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://login-qa.aa.aaa/oauth2/default/.well-known/openid-configuration'.
 ---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'https://login-qa.aa.aaa/oauth2/default/.well-known/openid-configuration'.
 ---> System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it. (login-qa.aa.aaa:443)
 ---> System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it.
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
   at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)
   at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
   --- End of inner exception stack trace ---
   at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
   at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
   at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
   --- End of inner exception stack trace ---
   at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
   at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleChallengeAsyncInternal(AuthenticationProperties properties)
   at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleChallengeAsync(AuthenticationProperties properties)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.ChallengeAsync(AuthenticationProperties properties)
   at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
   at Microsoft.AspNetCore.Mvc.ChallengeResult.ExecuteResultAsync(ActionContext context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAlwaysRunResultFilters>g__Awaited|27_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT`1.ProcessRequestAsync() 

Below is the code that I have in the program.cs file.


WebApplicationBuilder _appBuilder = WebApplication.CreateBuilder(args);
Microsoft.Extensions.Configuration.ConfigurationManager configuration = _appBuilder.Configuration;

configuration.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

IdentityModelEventSource.ShowPII = true;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;


_appBuilder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
   .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
     {
         options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
     })
   .AddOpenIdConnect(options =>
{
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.Authority = configuration.GetValue<string>("Config:Domain");
    options.ClientId = configuration.GetValue<string>("Config:ClientId");
    options.ClientSecret = configuration.GetValue<string>("Config:ClientSecret");
   
    options.GetClaimsFromUserInfoEndpoint = true;
    options.ResponseType = OpenIdConnectResponseType.Code;
    options.UseTokenLifetime = true;

    var webProxy = new WebProxy(new Uri(configuration["ProxyURL"]), BypassOnLocal: false);
    var proxyHttpClientHandler = new HttpClientHandler
    {
        Proxy = webProxy,
        UseProxy = true,
        SslProtocols = System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12
    };
    var httpClient = new HttpClient(proxyHttpClientHandler)
    {
        BaseAddress = new Uri(configuration["RedirectUri"]),
        Timeout = TimeSpan.FromMinutes(Convert.ToInt32(configuration.GetValue<int>("Timeout")))
    };

    options.BackchannelHttpHandler = new HttpClientHandler
    {
        ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
    };
    //options.SignedOutRedirectUri = "/Home/Logout";

    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.Scope.Add("email");
    options.SaveTokens = true;
    
    options.Events = new OpenIdConnectEvents
    {
        OnRedirectToIdentityProvider = ctx =>
        {
            // ctx.ProtocolMessage.RedirectUri = "https://localhost:44315/signin-oidc";
            ctx.ProtocolMessage.RedirectUri = configuration.GetValue<string>("RedirectUri");
            return Task.CompletedTask;
        },
        OnRedirectToIdentityProviderForSignOut = async ctx =>
        {
            
        },
        OnUserInformationReceived = async context =>
        {
            /*log.Info("OnUserInformationReceived");*/
            var identity = (ClaimsIdentity)context.Principal.Identity;
            string rawAccessToken = context.ProtocolMessage.AccessToken;
            string rawIdToken = context.ProtocolMessage.IdToken;
            var handler = new JwtSecurityTokenHandler();
            var accessToken = handler.ReadJwtToken(rawAccessToken);
            var idToken = handler.ReadJwtToken(rawIdToken);
        },
        OnTicketReceived = async context =>
        {
        
        },
        OnAuthenticationFailed = async context =>
        {
            
        }

    };
});

_appBuilder.Services.AddAuthorization();
_appBuilder.Services.AddAutoMapper(typeof(MappingProfile).Assembly);

_appBuilder.Services
    .AddMvc(config =>
    {
        ///enabled the authorization globally.
        var policy = new AuthorizationPolicyBuilder().
                    RequireAuthenticatedUser().
                    Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    })
    .AddSessionStateTempDataProvider()
    .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

_appBuilder.Services.AddOptions();
_appBuilder.Services.AddKendo();
_appBuilder.Services.AddMemoryCache();
_appBuilder.Services.AddSession();
_appBuilder.Services.AddResponseCaching();

_appBuilder.Services.AddRazorPages().AddRazorRuntimeCompilation();
_appBuilder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
_appBuilder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
});

_appBuilder.Services.Configure<ConfigurationSettings>(configuration.GetSection("ConfigurationSettings"));

_appBuilder.Services.AddHttpContextAccessor();


WebApplication application = _appBuilder.Build();

/*application.Use((context, next) =>
{
    context.Request.Scheme = "https";
    return next(context);
});*/
IdentityModelEventSource.ShowPII = true;
application.UseForwardedHeaders();

if (application.Environment.IsDevelopment())
{
   /* application.UseDeveloperExceptionPage();
    application.UseBrowserLink();*/
}
else
{
    application.UseHsts();
    /*application.UseExceptionHandler("/Error");*/
}

application.UseHttpsRedirection();
application.UseStaticFiles();
application.UsePathBase("/Home");

application.UseRouting();

application.UseAuthentication();
application.UseAuthorization();
application.UseSession();

application.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

    var builder = endpoints.MapDefaultControllerRoute();
    builder.RequireAuthorization();
});

application.MapRazorPages();
application.UseCookiePolicy();

application.Run();
0 Answers
Related