18

I am using ASP.NET 5, In my solution I have Web API, Identity Server and Angular 2 project and I am authenticating Angular 2 client by using Identity Server, Angular 2 client consumes web api by passing token in http request and web api authenticate token and gives response, for this I have written a custom attribute which checks that user is authenticated or not

When I consume API I am getting following exception and Web API returns 500 internal server error.

System.InvalidOperationException: IDX10803: Unable to obtain configuration from: 'http://xx.xx.xx.x:3926/.well-known/openid-configuration'. ---> System.IO.IOException: IDX10804: Unable to retrieve document from: 'http://xx.xx.xx.x:3926/.well-known/openid-configuration'. ---> System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond xx.xx.xx.x:3926 at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

Shashank Shekhar
  • 3,958
  • 2
  • 40
  • 52
amol
  • 1,497
  • 5
  • 17
  • 26
  • Does your webapi have access to the identity server ? i.e. can you hit the URL /.well-know/openid-configuration from the webapi environment ? – Karthik Jun 08 '16 at 05:06
  • Thanks for reply, Yes – amol Jun 08 '16 at 10:13
  • We have created a api method which is fetching configuration using "/.well-know/openid-configuration" URL. It is giving us proper response if we try to hit this api method from browser directly as well as from other application too (using jquery ajax get call) – amol Jun 08 '16 at 10:25
  • Is there a proxy configured on the system? When the application is deployed to IIS it won't have access to user configured proxies. You'll have to set it up on the OpenIdConnectOptions.BackchannelHttpHandler – Tratcher Jun 09 '16 at 23:26
  • Sounds like the server is either not running or you have disabled the metadata endpoint. – Brock Allen Jun 11 '16 at 16:11
  • Also sounds like this issue: https://stackoverflow.com/questions/37779542/a-task-was-canceled – Brock Allen Jun 13 '16 at 20:42

11 Answers11

18

I used something like this, and it resolved my issue.

services.AddAuthentication(o => {
            o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })            
        .AddCookie(cfg => cfg.SlidingExpiration = true)
        .AddJwtBearer(cfg =>
        {
            cfg.Audience = "http://localhost:4200/";
            cfg.Authority = "http://localhost:5000/";
            cfg.RequireHttpsMetadata = false;
            cfg.SaveToken = true;
            cfg.TokenValidationParameters = tokenValidationParameters;
            cfg.Configuration = new OpenIdConnectConfiguration();  <-- Most IMP Part
        });
Bharat
  • 5,869
  • 4
  • 38
  • 58
16

If identityserver and the access token validation middleware are hosted in the same application there is a race condition at startup.

The validation middleware tries to load the discovery document, which is not yet available.

In these scenarios, set the DelayLoadMetadata flag on the validation middleware to true.

If you disable the discovery endpoint altogether, you need to configure the issuer and key material on the validation options.

leastprivilege
  • 18,196
  • 1
  • 34
  • 50
7

The reason for this error was proxy and was able to resolve it by implementing the code below:

options.BackchannelHttpHandler = new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
                Proxy = new WebProxy(Configuration["System:Proxy"])
            };

If you are getting "unable to retrieve document from: '[pii is hidden]'" you need to add below to ConfigureServices:

    public void ConfigureServices(IServiceCollection services)
            {
......
IdentityModelEventSource.ShowPII = true;
    }

I hope this help.

  • `IdentityModelEventSource.ShowPII = true;` was indeed very helpful debugging a similar "Unable to retrieve document from.." error in my .Net 6.0 - API - JWT Bearer / Identity case. – Ian W Nov 25 '21 at 03:26
1

Check your appsettings.json tenant ID and make sure you didn't accidentally copy more than you need for the tenant ID.

Taraz
  • 1,242
  • 13
  • 13
1

In my case I was missing this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    app.UseIdentityServer();
    ...
}
Breeno
  • 3,007
  • 2
  • 31
  • 30
0

I've gotten this error message for a couple of reasons. One was solved with @leastprivilege answer. Another was that my certs-files in my Identity Server project had been lost in Version control. So i just replaced the broken files with the originals and then it worked.

Martin Johansson
  • 773
  • 1
  • 11
  • 27
0

Rebuilding my SSO project fixed my problem. Nuget packages were restored as well during rebuilding the project. Hope this helps you.

Nurhak Kaya
  • 1,470
  • 1
  • 18
  • 20
0

In case this helps anybody else.

I got this error after upgrading a project to .net core 2.0

the fix.

Change the name of the instance within appsettings.json instead of

"AADInstance": "https://login.microsoftonline.com/"

use

"Instance": "https://login.microsoftonline.com/"

N South
  • 9
  • 1
0

I ran into this issue testing on localhost with the dotnet run command. The call to /.well-known was performed on the wrong port. After adding a line to my startup class it works.

enter image description here

Michael Staples
  • 537
  • 7
  • 13
0

managed to solve it by changing the application pool identity from "Applicationpoolidentity" to "Built-in Account". in built in account service account name and its password is given

0

Alright, for us this issue was coming because our IT team had blocked the external calls from server, which means, when OpenIdConnect sdk tries fetch the said document, it will fail.

To overcome this without whitelisting external calls, we had to use a proxy in the OpenIdConnect. You might want to check Backchannel and BackchannelHttpHandler properties to use a proxy.

We had resolved these issues by using the proxy:

[TaskCanceledException: A task was canceled.]

The second issue that was resolved was:

[IOException: IDX20804: Unable to retrieve document from: 
'https://login.microsoftonline.com/Mytenantid/v2.0/.well-known/openid-configuration'.]
...
...
...

Task cancellation was coming because of the request being timed-out while fetching from the URL ('https://login.microsoftonline.com/Mytenantid/v2.0/.well-known/openid-configuration') which was being blocked by our server.

Jamshaid K.
  • 3,555
  • 1
  • 27
  • 42