user2370664
user2370664

Reputation: 423

.Net Core 3.1 react application with identity authentication - 403 Error Access is denied using provided credentials

When i attempt to access a .NET core 3.1 web application deployed in IIS i'm receiving the following error:

enter image description here

This error is misleading. I never had the opportunity to enter my login credentials because the login page didn't render. I created this project in Visual Studio 2019 with react and individual user account authentication. How can i make the login page the first to render?

Details about publishing to IIS: -From Visual Studio 2019 i published this project using the self-containted deployment type. Target framework = netcoreapp3.1, Target runtime win-x64 -I have also tried the Framework-Dependent deployment Type since the target server does have the .net core 3.1 hosting bundle installed.

Here's the web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <modules runAllManagedModulesForAllRequests="true" />
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\site_2020.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
  <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <rule name="Http To Https" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
        <defaultDocument enabled="false" />
  </system.webServer>
</configuration>

Here's appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost\\EXAMPLE_TEST;Database=SITE_TEST;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Debug",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "IdentityServer": {
    "Clients": {
      "site_2020": {
        "Profile": "IdentityServerSPA"
      }
    },
    "Key": {
      "Type": "Store",
      "StoreName": "Personal",
      "StoreLocation": "LocalMachine",
      "Name": "*.example.com"
    }
  },
  "JWT": {
    "Site": "https://secure.api.example.com",
    "SigninKey": "A Random Sting. wrkafjsdlkajreoiajfkljoiajweoir",
    "ExpiryInMinutes": "60"
  },
  "AllowedHosts": "*"
}

Here's startup.cs:

public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
readonly string AllowSpecificOrigins = "_allowSpecificOrigins";

public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o =>
            {               
                o.AddPolicy(AllowSpecificOrigins, b => b.WithOrigins("http://example.com", "https://example.com", 
                    "https://localhost:44378", "http://localhost:50296")
                .AllowAnyHeader()
                .AllowAnyMethod());
            });

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddRoles<IdentityRole>()
                .AddRoleManager<RoleManager<IdentityRole>>()
                .AddEntityFrameworkStores<ApplicationDbContext>();


            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();

            services.AddTransient<IProfileService, ProfileService>();

            services.Configure<JwtBearerOptions>(
                IdentityServerJwtConstants.IdentityServerJwtBearerScheme,
                options =>
                {
                    var onTokenValidated = options.Events.OnTokenValidated;

                    options.Events.OnTokenValidated = async context =>
                    {
                        await onTokenValidated(context);
                    };
                });

            services.AddDbContext<HcrDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddControllersWithViews();
            services.AddRazorPages();

            services.AddMvc();
            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });

            services.AddScoped<SiteInterface, SiteRepository>();

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/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.UseSpaStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();
            app.UseCors(AllowSpecificOrigins);
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }

Any help is greatly appreciated. The target server is Windows Server 2019 VM on Azure. The Azure security group does allow HTTP and HTTPS.

Upvotes: 1

Views: 2389

Answers (1)

devpro
devpro

Reputation: 365

I don't see any use of .UseCore() in Startup Configure() method.

Can you try with it between UseAuthorization and UseEndpoints?

app.UseAuthorization();

app.UseCors("AllowOrigin");

app.UseEndpoints(endpoints => ...);

You could also add AllowAnyHeader and AllowAnyMethod in ConfigureServices method.

services.AddCors(o =>
{               
    o.AddPolicy("AllowOrigin", builder => { 
        builder
            .WithOrigins("http://example.com", "https://example.com", "https://localhost:44378", "http://localhost:50296")
            .AllowAnyHeader()
            .AllowAnyMethod();
   });
});

Upvotes: 1

Related Questions