. Net Core 3.1 реагирует на приложение с аутентификацией идентификации - ошибка 403 Доступ запрещен с использованием предоставленных учетных данных - PullRequest
0 голосов
/ 22 февраля 2020

Когда я пытаюсь получить доступ к веб-приложению. NET core 3.1, развернутому в IIS, я получаю следующую ошибку:

enter image description here

Это ошибка вводит в заблуждение. У меня никогда не было возможности ввести свои учетные данные, потому что страница входа не отображалась. Я создал этот проект в Visual Studio 2019 с проверкой подлинности и индивидуальной учетной записью пользователя. Как сделать страницу входа первой для отображения?

Подробная информация о публикации в IIS: -Из Visual Studio 2019 я опубликовал этот проект, используя автономный тип развертывания. Target framework = netcoreapp3.1, Target runtime win-x64 -Я также попробовал зависящий от платформы тип развертывания, поскольку на целевом сервере установлен хост-пакет. net core 3.1.

Вот 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>

Вот настройки приложения. 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:

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

Любая помощь с благодарностью. Целевым сервером является Windows Server 2019 VM на Azure. Группа безопасности Azure разрешает HTTP и HTTPS.

1 Ответ

0 голосов
/ 24 февраля 2020

Я не вижу никакого использования .UseCore () в методе запуска Configure ().

Можете ли вы попробовать использовать его между UseAuthorization и UseEndpoints?

app.UseAuthorization();

app.UseCors("AllowOrigin");

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

Вы также можете добавьте AllowAnyHeader и AllowAnyMethod в метод ConfigureServices.

services.AddCors(o =>
{               
    o.AddPolicy("AllowOrigin", builder => { 
        builder
            .WithOrigins("http://example.com", https://example.com", "https://localhost:44378", "http://localhost:50296")
            .AllowAnyHeader()
            .AllowAnyMethod();
   });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...