SocketException: No connection could be made because the target machine actively refused it

Hi all,

I’m testing on our oktapreview server for our org. We are able to set up openid successfully on the preview server following the tutorial (https://developer.okta.com/quickstart/#/okta-sign-in-page/dotnet/aspnetcore) pretty faithfully. However, when I upgrade to .net core 2.1, it immediately stops working on any authorized endpoint (this is the response we get from an authorized endpoint)

Any reason why upgrading from .net core 2.0 to 2.1 would be the isolating issue? 2.1 offers some really nice speedups, we’d like to avoid downgrading.

Thanks,
Camden

That seems odd. I’ve tested Okta with aspnetcore 2.1 recently and it worked. Can you post your Startup code (scrubbed for sensitive values)?

It might be even easier with this new package we just published: https://github.com/okta/okta-aspnet/

    public void ConfigureServices(IServiceCollection services)
    {
      services.Configure<IISOptions>(options => { options.ForwardClientCertificate = true; });

      services.AddResponseCompression(options =>
      {
        options.MimeTypes = new List<string> { "image/jpeg", "image/png", "image/jpg" };
      });

      services.AddCors(options =>
      {
        options.AddPolicy("CorsPolicy",
          builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials());
      }).AddMvc(options =>
      {
        options.ValueProviderFactories.Insert(0, new SeparatedQueryStringValueProviderFactory(","));
        options.Filters.Add(new ProducesAttribute("application/json"));
        options.Filters.Add(new CustomExceptionFilter());
        options.CacheProfiles.Add("Default",
          new CacheProfile()
          {
            Duration = 60
          });
        options.CacheProfiles.Add("Never",
          new CacheProfile()
          {
            Location = ResponseCacheLocation.None,
            NoStore = true
          });
      }).AddJsonOptions(options =>
      {
          // Have JSON response keys use consistent formatting
          options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
          options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
      });

      services.AddAuthentication(sharedOptions =>
      {
        sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
      })
      .AddCookie()
      .AddOpenIdConnect(options =>
      {
          options.ClientId = Configuration["okta:ClientId"];
          options.ClientSecret = Configuration["okta:ClientSecret"];
          options.Authority = Configuration["okta:Issuer"];
          options.CallbackPath = "/authorization-code/callback";
          options.ResponseType = "code";
          options.SaveTokens = true;
          options.UseTokenLifetime = false;
          options.GetClaimsFromUserInfoEndpoint = true;
          options.Scope.Add("openid");
          options.Scope.Add("profile");
          options.TokenValidationParameters = new TokenValidationParameters
          {
              NameClaimType = "name"
          };
      });


      services.AddMvc();

      //swagger and other sensitive things
    }

public void Configure(...)
    {
      app.UseSwagger();
      app.UseSwaggerUI(c =>
      {
        c.SwaggerEndpoint("v1/swagger.json", "...");
      });

      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      if (env.IsEnvironment("Docker"))
      {
        ConfigureDocker(context, workdayContext, args);
      }

      app.UseResponseCompression();

      var fileProvider = new S3FileProvider(s3, "...");

      app.UseCors("CorsPolicy");
      app.UseStaticFiles(new StaticFileOptions {
        FileProvider = fileProvider,
        RequestPath = "/images",
        OnPrepareResponse = ctx => {
          ctx.Context.Response.Headers.Add("Cache-Control", "public,max-age=600");
          ctx.Context.Response.Headers["Access-Control-Allow-Origin"] = "*";
        }
      });

      //Order is important--if the logger comes before the static file middleware,
      //then images will get logged!
      if (env.IsProduction())
      {
        app.UseMiddleware<LoggingMiddleware>();
      }

      app.UseAuthentication();

      app.UseMvc();
    }```

I actually just tried that package (after seeing it in a stack overflow comment). Same error, unfortunately.

Weird. Does aspnetcore show an error in the logs?


      Execution plan of authorization filters (in the following order): Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Debug: Execution plan of authorization filters (in the following order): Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Execution plan of resource filters (in the following order): Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.SaveTempDataFilter
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Debug: Execution plan of resource filters (in the following order): Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.SaveTempDataFilter
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Execution plan of action filters (in the following order): Microsoft.AspNetCore.Mvc.Internal.ControllerActionFilter (Order: -2147483648), Microsoft.AspNetCore.Mvc.ModelBinding.UnsupportedContentTypeFilter, Microsoft.AspNetCore.Mvc.Internal.ResponseCacheFilter
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Debug: Execution plan of action filters (in the following order): Microsoft.AspNetCore.Mvc.Internal.ControllerActionFilter (Order: -2147483648), Microsoft.AspNetCore.Mvc.ModelBinding.UnsupportedContentTypeFilter, Microsoft.AspNetCore.Mvc.Internal.ResponseCacheFilter
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Execution plan of exception filters (in the following order): [...].CustomExceptionFilter
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Debug: Execution plan of exception filters (in the following order): [...].CustomExceptionFilter
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Execution plan of result filters (in the following order): Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.SaveTempDataFilter, Microsoft.AspNetCore.Mvc.ProducesAttribute (Order: 0)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Debug: Execution plan of result filters (in the following order): Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.SaveTempDataFilter, Microsoft.AspNetCore.Mvc.ProducesAttribute (Order: 0)
trce: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Authorization Filter: Before executing OnAuthorizationAsync on filter Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Trace: Authorization Filter: Before executing OnAuthorizationAsync on filter Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter.
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed.
trce: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Authorization Filter: After executing OnAuthorizationAsync on filter Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Trace: Authorization Filter: After executing OnAuthorizationAsync on filter Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
trce: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[4]
      Before executing action result Microsoft.AspNetCore.Mvc.ChallengeResult.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Trace: Before executing action result Microsoft.AspNetCore.Mvc.ChallengeResult.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes ().
trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[4]
      Entering Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler's HandleUnauthorizedAsync.
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler:Trace: Entering Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler's HandleUnauthorizedAsync.
trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[5]
      Using properties.RedirectUri for 'local redirect' post authentication: 'http://localhost:5000/api/v1/endpoint'.

Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.1.2\Microsoft.Win32.Primitives.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
trce: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[5]
      After executing action result Microsoft.AspNetCore.Mvc.ChallengeResult.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Trace: After executing action result Microsoft.AspNetCore.Mvc.ChallengeResult.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]


fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: '[PII is hidden]'. ---> System.IO.IOException: IDX20804: Unable to retrieve document from: '[PII is hidden]'. ---> System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   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.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.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAlwaysRunResultFilters()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.ResponseCompression.ResponseCompressionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request.

System.InvalidOperationException: IDX20803: Unable to obtain configuration from: '[PII is hidden]'. ---> System.IO.IOException: IDX20804: Unable to retrieve document from: '[PII is hidden]'. ---> System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   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.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.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAlwaysRunResultFilters()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.ResponseCompression.ResponseCompressionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
dbug: Microsoft.AspNetCore.Server.Kestrel[9]
      Connection id "0HLFEAO53H3P0" completed keep alive response.

trace log from asp.net core.

Any guidance on this?

We solved our issue. We have a proxy server on prem. If you have a similar situation, add this to your AddOpenIdConnect options:

var proxy = new WebProxy("proxy_server_url") {
    Credentials = CredentialCache.DefaultNetworkCredentials
};
options.BackchannelHttpHandler = new HttpClientHandler() { Proxy = proxy };

Hope this helps someone else.

1 Like

Ah, makes sense. Didn’t even think of a proxy. Thanks for posting your solution!

1 Like

This error is a network-related error occurred while establishing a connection to the Server. It means that the error is occurring because there is no server listening at the hostname and port you assigned. It happens that something is preventing a connection to the port or hostname. Either there is a firewall blocking the connection or the process that is hosting the service is not listening on that specific port. This may be because it is not running at all or because it is listening on a different port. So, no connection can be established. The solution to this problem is that connect to the same end point your server is listening on.