locked
Identity Server 4 Not working after uploading to Server/Hosting RRS feed

  • Question

  • User2041008840 posted

    Hello, 
    the Identity Server 4 project not working after uploading to the hosting. 
    showing error - An error occurred while starting the application. 
    I think its from Startup.cs

      public class Startup
        {
            public IWebHostEnvironment Environment { get; }
            public IConfiguration Configuration { get; }
    
            public Startup(IWebHostEnvironment environment, IConfiguration configuration)
            {
                Environment = environment;
                Configuration = configuration;
            }
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllersWithViews();
                services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
                services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
    
    
                var filePath = Path.Combine(Environment.ContentRootPath, "is_Cert.pfx");
                var certificate = new X509Certificate2(filePath, "He4bd");
                var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
                var builder = services.AddIdentityServer(options =>
                {
                    options.Events.RaiseErrorEvents = true;
                    options.Events.RaiseInformationEvents = true;
                    options.Events.RaiseFailureEvents = true;
                    options.Events.RaiseSuccessEvents = true;
                    // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
                    options.EmitStaticAudienceClaim = true;
                })
                 //.AddInMemoryIdentityResources(Config.IdentityResources)
                 //.AddInMemoryApiScopes(Config.ApiScopes)
                 //.AddInMemoryClients(Config.Clients)
    
                 .AddConfigurationStore(options =>
                 {
                     options.ConfigureDbContext = b => b.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                         sql => sql.MigrationsAssembly(migrationsAssembly));
                 })
                    .AddOperationalStore(options =>
                    {
                        options.ConfigureDbContext = b => b.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                            sql => sql.MigrationsAssembly(migrationsAssembly));
                    })
                  .AddAspNetIdentity<ApplicationUser>();
                  .AddSigningCredential(certificate); //self sign certificate 
    
                //to get Data from Database not from In Memory. Comment above InMemory Dependancies for this.
    
               
                //builder.AddDeveloperSigningCredential();
    
                services.AddAuthentication().AddGoogle(options =>
                {
                    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
    
                    // register your IdentityServer with Google at https://console.developers.google.com
                    // enable the Google+ API
                    // set the redirect URI to https://localhost:5001/signin-google
    
                    options.ClientId = "11366420-k6djmgv5752pkoulml0c6oe7.apps.googleusercontent.com";
                    options.ClientSecret = "OOvPRckkDBSobOgYBrO5";
                });
            }
    
            public void Configure(IApplicationBuilder app)
            {
                // this will do the initial DB population
               // InitializeDatabase(app);
                if (Environment.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    //app.UseDatabaseErrorPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    app.UseHsts();
                }
                app.UseHttpsRedirection();
                app.UseStaticFiles();
    
                app.UseRouting();
                app.UseIdentityServer();
                app.UseAuthorization();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapDefaultControllerRoute();
                });
            }

    If I remove the .AddSigningCredential(Certificate) then its working but the after login showing the no certificate found. 

    Help me please...


    Saturday, March 6, 2021 4:50 PM

All replies

  • User475983607 posted

    I assume you are receiving null error because the startup code cannot find the certificate on the server.  I recommend following standard troubleshooting steps found in the openly published documentation to get the actual error.  Enable logging in the web.config which assumes you designed logging into your code.  You can also start the application using dotnet run and look for the exception in the console.

    dotnet applicationName.dll

    https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-run

    Most likely you need to export the certificate to the new host.  

    Saturday, March 6, 2021 5:25 PM
  • User2041008840 posted

    I am not getting any stdout logs on hosting. I also create a Logs folder into directory but not getting any logs.

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <location path="." inheritInChildApplications="false">
        <system.webServer>
          <handlers>
            <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
          </handlers>
          <aspNetCore processPath=".\IAccounts.exe" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
        </system.webServer>
      </location>
    </configuration>
    <!--ProjectGuid: 16ebb577-c84d-4e7e-9c1c-02d0d3bb382e-->

    Sunday, March 7, 2021 9:27 AM
  • User2041008840 posted

    mgebhard

    I assume you are receiving null error because the startup code cannot find the certificate on the server.  I recommend following standard troubleshooting steps found in the openly published documentation to get the actual error.  Enable logging in the web.config which assumes you designed logging into your code.  You can also start the application using dotnet run and look for the exception in the console.

    dotnet applicationName.dll

    https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-run

    Most likely you need to export the certificate to the new host.  

    I am getting this path as Environment.ContentRootPath after I print it in viewbag  - "C:\Inetpub\vhosts\istech.in\accounts.istech.in"
    is there any need to change? the path is correct. on local/Development it works fine with same code.

    dotnet applicationName.dll works fine and I added ".pfx" file into it. 

    But after publish project not working. I didnt getting any stdout logs.  

    Sunday, March 7, 2021 11:23 AM
  • User475983607 posted

    dotnet applicationName.dll works fine and I added ".pfx" file into it. 

    But after publish project not working. I didnt getting any stdout logs.

    I assume you are the admin on the server.  If dotnet app.dll works then most likely the application identity does not have read/write access to the certificate location.  Grant the application pool identity access to the file location.

    Sunday, March 7, 2021 12:22 PM
  • User2041008840 posted

    so finally stdout logs enables and working 
    this is the info I am getting


    warn: Microsoft.AspNetCore.DataProtection.Repositories.EphemeralXmlRepository[50]
          Using an in-memory repository. Keys will not be persisted to storage.
    warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[59]
          Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.
    warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
          No XML encryptor configured. Key {d0ed70a6-9bfb-4594-a8a5-81bc53021d90} may be persisted to storage in unencrypted form.
    crit: Microsoft.AspNetCore.Hosting.Diagnostics[6]
          Application startup exception
          Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The system cannot find the file specified.
             at Internal.Cryptography.Pal.CertificatePal.FilterPFXStore(ReadOnlySpan`1 rawData, SafePasswordHandle password, PfxCertStoreFlags pfxCertStoreFlags)
             at Internal.Cryptography.Pal.CertificatePal.FromBlobOrFile(ReadOnlySpan`1 rawData, String fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
             at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags)
             at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password)
             at InnovusAccounts.Startup.ConfigureServices(IServiceCollection services)
             at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
             at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
             at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)
             at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass9_0.<Invoke>g__Startup|0(IServiceCollection serviceCollection)
             at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)
             at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass8_0.<Build>b__0(IServiceCollection services)
             at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services, Object instance)
          --- End of stack trace from previous location ---
             at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.<UseStartup>b__1(IApplicationBuilder app)
             at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
             at Microsoft.AspNetCore.Server.IISIntegration.IISSetupFilter.<>c__DisplayClass4_0.<Configure>b__0(IApplicationBuilder app)
             at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
             at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
    info: Microsoft.Hosting.Lifetime[0]
          Now listening on: http://127.0.0.1:12813
    info: Microsoft.Hosting.Lifetime[0]
          Application started. Press Ctrl+C to shut down.
    info: Microsoft.Hosting.Lifetime[0]
          Hosting environment: Production
    info: Microsoft.Hosting.Lifetime[0]
          Content root path: C:\Inetpub\vhosts\istech.in\accounts.istech.in

    I saved the .pfx file here C:\Inetpub\vhosts\istech.in\accounts.istech.in

    Sunday, March 7, 2021 5:00 PM
  • User475983607 posted

    Did you actually take the time to read the error?  

    The system cannot find the file specified.

    The file was not found or the application does not have access to the file location.  Since you said dotnet app.dll works and does not throw an exception, I assume the web application does not have access to the file path as explained in my previous post.  Grant R/W access to the application pool identity.

    Sunday, March 7, 2021 5:09 PM
  • User2041008840 posted

    I gave the Grant R/W Application Pool to the folder and file but it still don't work. 

    is there any option like to save the pfx file in database and retreive it on startup.cs? if yes how? 
    Or is there any options? 

    Monday, March 8, 2021 2:04 PM
  • User475983607 posted

    Prathamesh Shende

    I gave the Grant R/W Application Pool to the folder and file but it still don't work. 

    You said the command dotnet app.dll started identity server without error. I assumed that means the code found the certificate.  Is that true or does dotnet app.dll also fail with "The system cannot find the file specified."?

    Prathamesh Shende

    is there any option like to save the pfx file in database and retreive it on startup.cs? if yes how? 
    Or is there any options? 

    I store certificates in the standard certificate store in windows and grant the application pool access to the certificate.  

    I'm not sure how to help you.   I suspect the file does not exist in the or yo made a mistake granting access to the file.

    Monday, March 8, 2021 2:54 PM
  • User2041008840 posted

    mgebhard

    Prathamesh Shende

    I gave the Grant R/W Application Pool to the folder and file but it still don't work. 

    You said the command dotnet app.dll started identity server without error. I assumed that means the code found the certificate.  Is that true or does dotnet app.dll also fail with "The system cannot find the file specified."?

    Prathamesh Shende

    is there any option like to save the pfx file in database and retreive it on startup.cs? if yes how? 
    Or is there any options? 

    I store certificates in the standard certificate store in windows and grant the application pool access to the certificate.  

    I'm not sure how to help you.   I suspect the file does not exist in the or yo made a mistake granting access to the file.

    yes I check the file using dotnet Project.dll using powershell the file is in release folder of project. the project is on my local computer and I also check on both environment dev and production and it works fine. 
    and I also apply the 
    permissions RW of Application Pool
    https://ibb.co/wd5J0rT through the plesk panel

    Monday, March 8, 2021 7:09 PM