简体   繁体   English

.Net Core 3.1 使用身份验证反应应用程序 - 403 错误使用提供的凭据拒绝访问

[英].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:当我尝试访问部署在 IIS 中的 .NET core 3.1 Web 应用程序时,我收到以下错误:

在此处输入图像描述

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.我在 Visual Studio 2019 中使用 react 和个人用户帐户身份验证创建了这个项目。 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.有关发布到 IIS 的详细信息:-从 Visual Studio 2019 开始,我使用自包含部署类型发布了此项目。 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.目标框架 = netcoreapp3.1,目标运行时 win-x64 -我也尝试了框架依赖部署类型,因为目标服务器确实安装了 .net core 3.1 托管包。

Here's the web.config:这是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:这是 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:这是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.目标服务器是 Azure 上的 Windows Server 2019 VM。 The Azure security group does allow HTTP and HTTPS. Azure 安全组确实允许 HTTP 和 HTTPS。

I don't see any use of .UseCore() in Startup Configure() method.我在 Startup Configure() 方法中看不到 .UseCore() 的任何用途。

Can you try with it between UseAuthorization and UseEndpoints?您可以在 UseAuthorization 和 UseEndpoints 之间尝试使用它吗?

app.UseAuthorization();

app.UseCors("AllowOrigin");

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

You could also add AllowAnyHeader and AllowAnyMethod in ConfigureServices method.您还可以在 ConfigureServices 方法中添加 AllowAnyHeader 和 AllowAnyMethod。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET 核心 3.1 - 访问被拒绝 - ASP.NET Core 3.1 - Access denied .NET Core 和 IIS 间歇性 403 访问被拒绝 - .NET Core and IIS Intermittent 403 Access Denied 不使用Identity的.net core 2.2应用程序的JWT身份验证 - JWT Authentication for .net core 2.2 application not using Identity 使用.Net Core 3.1 Razor页面应用程序访问Class中的Session - Access Session in Class using .Net Core 3.1 Razor Pages Application ASP.Net Core 3.1 WebClient 使用应用程序池凭据访问其他具有 Windows 身份验证的 API - ASP.Net Core 3.1 WebClient to Use Application Pool Credential to Access Other API that has Windows Authentication 禁止访问 .NET Core 3.1 MVC 中的所有身份页面 - Disable access to all Identity pages in .NET Core 3.1 MVC 使用 .NET Core Web API 3.1 的 JWT 基于角色的授权时出现 403 错误 - 403 Error on JWT Role Based Authorization using .NET Core Web API 3.1 .Net Core 3.1 MVC 身份验证个人用户帐户和 ASP.NET 核心项目中的脚手架身份 - .Net Core 3.1 MVC Authentication Individual User Accounts and Scaffold Identity in ASP.NET Core projects .net core 3.1 身份:cookie 创建“请求太长”错误 - .net core 3.1 identity: cookies create a "request too long" error 注销时 ASP NET CORE 身份重定向到拒绝访问 - ASP NET CORE Identity redirecting to Access Denied when logout
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM