.Net Core 3.1使用身份验证对应用程序进行反应-使用提供的凭据拒绝403错误访问 [英] .Net Core 3.1 react application with identity authentication - 403 Error Access is denied using provided credentials

查看:66
本文介绍了.Net Core 3.1使用身份验证对应用程序进行反应-使用提供的凭据拒绝403错误访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试访问IIS中部署的.NET Core 3.1 Web应用程序时,出现以下错误:

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

此错误具有误导性.因为登录页面未呈现,所以我从来没有机会输入登录凭据. 我在Visual Studio 2019中使用React和单个用户帐户身份验证创建了这个项目.如何使登录页面最先呈现?

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?

有关发布到IIS的详细信息: -从Visual Studio 2019开始,我使用自包含的部署类型发布了此项目.目标框架= netcoreapp3.1,目标运行时win-x64 -我还尝试了框架相关的部署类型,因为目标服务器确实安装了.net core 3.1托管捆绑包.

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.

这是web.config:

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>

这是appsettings.json:

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": "*"
}

这是startup.cs:

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");
                }
            });
        }

任何帮助将不胜感激.目标服务器是Azure上的Windows Server 2019 VM. Azure安全组确实允许HTTP和HTTPS.

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

推荐答案

在启动Configure()方法中看不到对.UseCore()的任何使用.

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

您可以在UseAuthorization和UseEndpoints之间尝试使用它吗?

Can you try with it between UseAuthorization and UseEndpoints?

app.UseAuthorization();

app.UseCors("AllowOrigin");

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

您还可以在ConfigureServices方法中添加AllowAnyHeader和AllowAnyMethod.

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();
   });
});

这篇关于.Net Core 3.1使用身份验证对应用程序进行反应-使用提供的凭据拒绝403错误访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆