title: Network Error at XMLHttpRequest.s.onerror (oidc-client.min.js:3) with angular 7 and Asp.net core 2.2
body: <p>Trying to use the identity server 4 for authentication in asp.net core 2.2 with angular 7 application.</p>
  
  <p><strong>oidc-login-redirect.html</strong></p>
  
  <pre><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/oidc-client/1.5.4/oidc-client.min.js"&gt;&lt;/script&gt;
  &lt;script&gt;
    var config = {
      userStore: new Oidc.WebStorageStateStore({ store: window.localStorage })
    };
    var mgr = new Oidc.UserManager(config);
    mgr.signinRedirectCallback().then(() =&gt; {
          window.history.replaceState({},
              window.document.title,
              window.location.origin);
          window.location = "/";
      }, error =&gt; {
          console.error(error);
      });
  
  &lt;/script&gt;
  </code></pre>
  
  <p><strong>Angular Auth Service code</strong></p>
  
  <pre><code>export class AuthServiceJwt implements CanActivate {
      _userManager: UserManager;
      _user: User;
      constructor(public router: Router) {
          //Log.logger = console;
          var config = {
              authority: environment.authority,
              client_id: environment.client_id,
              redirect_uri: `${environment.client_root_url}assets/oidc-login-redirect.html`,
              scope: environment.scope,
              response_type: environment.response_type,
              post_logout_redirect_uri: `${environment.client_root_url}?postLogout=true`,
              userStore: new WebStorageStateStore({ store: window.localStorage }),
              automaticSilentRenew: true,
              silent_redirect_uri: `${environment.client_root_url}assets/silent-redirect.html`
          };
          this._userManager = new UserManager(config);
          this._userManager.getUser().then(user =&gt; {
              if (user &amp;&amp; !user.expired) {
                  this._user = user;
                  //this.loadSecurityContext();
              }
          });
          this._userManager.events.addUserLoaded(args =&gt; {
              this._userManager.getUser().then(user =&gt; {
                  this._user = user;
                  //this.loadSecurityContext();
              });
          });
      }
  
  
      login(): Promise&lt;any&gt; {
          return this._userManager.signinRedirect();
      }
  }
  </code></pre>
  
  <p><strong>Environment.ts</strong></p>
  
  <pre><code>export const environment = {
      authority: 'https://localhost:44305/',
        client_id: 'mero-rental-angular-client',
        response_type: 'id_token token',
        scope: 'openid mero-rental-client-api profile',
        client_root_url: 'http://localhost:4200/'
  }
  </code></pre>
  
  <p>Server side Code.
  <strong>CustomProfileService.cs</strong></p>
  
  <pre><code>public class CustomProfileService : IProfileService
      {
          private readonly IUserClaimsPrincipalFactory&lt;ApplicationUserViewModel&gt; _claimsFactory;
          private readonly UserManager&lt;ApplicationUserViewModel&gt; _userManager;
  
          public CustomProfileService(UserManager&lt;ApplicationUserViewModel&gt; userManager, IUserClaimsPrincipalFactory&lt;ApplicationUserViewModel&gt; claimsFactory)
          {
              _userManager = userManager;
              _claimsFactory = claimsFactory;
          }
  
          public async Task GetProfileDataAsync(ProfileDataRequestContext context)
          {
              var sub = context.Subject.GetSubjectId();
              var user = await _userManager.FindByIdAsync(sub);
              var principal = await _claimsFactory.CreateAsync(user);
  
              var claims = principal.Claims.ToList();
  
              if (user.Email == "admin@identity.localhost")
              {
                  claims.Add(new Claim(JwtClaimTypes.Role, "Admin"));
              }
              context.IssuedClaims = claims;
          }
  
          public async Task IsActiveAsync(IsActiveContext context)
          {
              var sub = context.Subject.GetSubjectId();
              var user = await _userManager.FindByIdAsync(sub);
              context.IsActive = user != null;
          }
      }
  </code></pre>
  
  <p><strong>Startup.cs</strong></p>
  
  <p>public void ConfigureServices(IServiceCollection services)
          {</p>
  
  <pre><code>        services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
          services.AddIdentity&lt;ApplicationUserViewModel, IdentityRole&gt;()
              .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;()
              .AddDefaultTokenProviders();
          services.AddTransient&lt;IProfileService, CustomProfileService&gt;();
          services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
          var builder = services.AddIdentityServer(options =&gt;
          {
              options.Events.RaiseErrorEvents = true;
              options.Events.RaiseInformationEvents = true;
              options.Events.RaiseFailureEvents = true;
              options.Events.RaiseSuccessEvents = true;
          })
              .AddInMemoryIdentityResources(GetIdentityResources())
              .AddInMemoryApiResources(GetApiResources())
              .AddInMemoryClients(GetClients())
              .AddAspNetIdentity&lt;ApplicationUserViewModel&gt;()
              .AddProfileService&lt;CustomProfileService&gt;();
          builder.AddDeveloperSigningCredential();
      }
  
      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
          }
          else
          {
              app.UseExceptionHandler("/Home/Error");
              // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
              app.UseHsts();
          }
  
          app.UseHttpsRedirection();
          app.UseStaticFiles();
  
          app.UseCors(builder =&gt;
          {
              builder.AllowAnyOrigin()
              .AllowAnyHeader()
              .AllowAnyMethod();
          });
          app.UseMvc(routes =&gt;
          {
              routes.MapRoute(
                  name: "default",
                  template: "{controller=Home}/{action=Index}/{id?}");
          });
          app.UseIdentityServer();
          app.UseAuthentication();
      }
  </code></pre>
  
  <p><strong>config class</strong></p>
  
  <pre><code>public partial class Startup
      {
          public IEnumerable&lt;ApiResource&gt; GetApiResources()
          {
              return new List&lt;ApiResource&gt;
              {
                  new ApiResource( ConstantValue.ClientDashApi, ConstantValue.ClientApi)
              };
          }
  
  
          public IEnumerable&lt;Client&gt; GetClients()
          {
              var client = new List&lt;Client&gt;
              {
                  new Client
                  {
                       ClientId = ConstantValue.ClientId,
                      ClientName = ConstantValue.ClientName,
                      AllowedGrantTypes = GrantTypes.Implicit,
                      AllowAccessTokensViaBrowser = true,
                      RequireConsent = false,
                      RedirectUris =           { string.Format("{0}/{1}", Configuration["IdentityServerUrls:ClientUrl"], "assets/oidc-login-redirect.html"), string.Format("{0}/{1}", Configuration["IdentityServerUrls:ClientUrl"], "assets/silent-redirect.html") },
                      PostLogoutRedirectUris = { string.Format("{0}?{1}", Configuration["IdentityServerUrls:ClientUrl"] , "postLogout=true") },
                      AllowedCorsOrigins =     { Configuration["IdentityServerUrls: ClientUrl"] },
  
                      AllowedScopes =
                      {
                          IdentityServerConstants.StandardScopes.OpenId,
                          IdentityServerConstants.StandardScopes.Profile,
                          ConstantValue.ClientDashApi
                      },
                      IdentityTokenLifetime=120,
                      AccessTokenLifetime=120
  
                  },
              };
              return client;
          }
  
          public IEnumerable&lt;IdentityResource&gt; GetIdentityResources()
          {
              return new List&lt;IdentityResource&gt;
              {
                  new IdentityResources.OpenId(),
                  new IdentityResources.Profile()
              };
          }
      }
  </code></pre>
  
  <p><strong>Constant Value</strong></p>
  
  <pre><code>public static class ConstantValue
      {
          public const string ClientId = "mero-rental-angular-client";
          public const string ClientName = "mero-rental";
          public const string ClientDashApi = "mero-rental-client-api";
          public const string ClientApi = "Mero Rental Client API";
  
      }
  </code></pre>
  
  <p><strong>Appsetting.json</strong></p>
  
  <pre><code>"IdentityServerUrls": {
      "Authority": "https://localhost:5002/",
      "ClientUrl": "http://localhost:4200"
    }
  </code></pre>
  
  <p>I, am able to login successfully and able to see the jwt token with bearer code. But on the browser keep getting an error as shown below.</p>
  
  <p><a href="https://i.stack.imgur.com/jz4Mb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jz4Mb.png" alt="more details image"></a></p>
  
  <p>When decode the image in JWT.IO website found the below information.
  <a href="https://i.stack.imgur.com/YLYiK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YLYiK.png" alt="jwt info"></a></p>
  
  <p><a href="https://i.stack.imgur.com/PXNIY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PXNIY.png" alt="addede more details"></a></p>
  
  <p>Done some research - <a href="https://github.com/IdentityServer/IdentityServer4/issues/1194" rel="nofollow noreferrer">https://github.com/IdentityServer/IdentityServer4/issues/1194</a>
  <a href="https://github.com/IdentityServer/IdentityServer4/issues/1249" rel="nofollow noreferrer">https://github.com/IdentityServer/IdentityServer4/issues/1249</a>
  <a href="https://github.com/IdentityServer/IdentityServer4/issues/1608" rel="nofollow noreferrer">https://github.com/IdentityServer/IdentityServer4/issues/1608</a>
  <a href="http://docs.identityserver.io/en/latest/endpoints/userinfo.html" rel="nofollow noreferrer">http://docs.identityserver.io/en/latest/endpoints/userinfo.html</a></p>
  
  <p><a href="https://i.stack.imgur.com/Vp8EK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vp8EK.png" alt="added debug details"></a></p>
  
  <p><strong>Errors</strong></p>
  
  <pre><code>GET https://localhost:44305/connect/userinfo net::ERR_INVALID_HTTP_RESPONSE
  oidc-login-redirect.html:13 Error: Network Error
      at XMLHttpRequest.s.onerror (oidc-client.min.js:3)
  mgr.signinRedirectCallback.then.error @ oidc-login-redirect.html:13
  Promise.then (async)
  (anonymous) @ oidc-login-redirect.html:7
  </code></pre>