My As pNet Core 3.1 Identity Pages дают 404 в IdentityServer4. Как я могу получить к ним доступ? Это проблема с маршрутом? - PullRequest
1 голос
/ 17 июня 2020

Я следил за учебником Deblokt здесь , в котором подробно объясняется, как настроить IdentityServer4 в net core 3.1 и использовать AspNetCore Identity для пользовательского хранилища.

Я могу войти на мой IdentityServer с https://localhost: 5001 / Account / Login url (и выйти из системы) нормально ... Но я не могу получить доступ к страницам As pNet Core Identity (например, Register / ForgotPassword / AccessDenied et c). Я их выстроил, поэтому они находятся в разделах «Области / Идентификация / Страницы / Учетная запись» ... но когда я перехожу к ним, например, https://localhost: 5001 / Identity / Account / Register , я просто получаю 404 не найден.

Я не уверен, но подозреваю, что это может быть проблема с маршрутизацией, поэтому я исследовал возможность маршрутизации для этих страниц, но примеры, которые я видел для IdentityServer, предназначены для Core2.1 и используют приложение. Используйте MVC ... которого нет в моем запуске. Я попытался включить его, но получаю сообщение об ошибке:

Маршрутизация конечных точек не поддерживает 'IApplicationBuilder.Use Mvc (...)'. Чтобы использовать 'IApplicationBuilder.Use Mvc', установите 'MvcOptions.EnableEndpointRouting = false' внутри 'ConfigureServices (...)'

Итак, где мне go отсюда?

Я загрузил с GitHub сопутствующие руководства, но это решение Core 2.1, поэтому подозреваю, что это руководство представляет собой переписанную / обновленную версию до 3.1.

Это мой файл запуска ...

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)
        {
            // uncomment, if you want to add an MVC-based UI
            services.AddControllersWithViews();
            services.AddRazorPages(); // I recently added this, but made no difference

            string connectionString = Configuration.GetConnectionString("DefaultConnection");

            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext<IdentityDbContext>(options =>
                options.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly))
            );

            services.AddDbContext<Data.ConfigurationDbContext>(options => options.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly)));

            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.SignIn.RequireConfirmedEmail = true;
            })
            .AddEntityFrameworkStores<IdentityDbContext>()
            .AddDefaultTokenProviders();

            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents = true;
                options.Events.RaiseSuccessEvents = true;
                options.UserInteraction.LoginUrl = "/Account/Login";
                options.UserInteraction.LogoutUrl = "/Account/Logout";
                options.Authentication = new AuthenticationOptions()
                {
                    CookieLifetime = TimeSpan.FromHours(10), // ID server cookie timeout set to 10 hours
                    CookieSlidingExpiration = true
                };
            })
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = b => b.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
            })
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = b => b.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
                options.EnableTokenCleanup = true;
            })
            .AddAspNetIdentity<ApplicationUser>();

            X509Certificate2 cert = null;

            using (X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
            {
                certStore.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certCollection = certStore.Certificates.Find(
                    X509FindType.FindByThumbprint,
                    // Replace below with your cert's thumbprint
                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" // Replaced for this post
                    ,
                    false);
                // Get the first cert with the thumbprint
                if (certCollection.Count > 0)
                {
                    cert = certCollection[0];
                }
            }

            // Fallback to local file for development
            if (cert == null)
            {
                cert = new X509Certificate2(Path.Combine(Environment.ContentRootPath, "xxxxxxxxx.pfx"), "xxxxxxxxxxxxxxxxxxxxx"); // Replaced for this post
            }

            // not recommended for production - you need to store your key material somewhere secure
            //builder.AddDeveloperSigningCredential();
            builder.AddSigningCredential(cert);
            builder.AddValidationKey(cert);

            services.AddScoped<IProfileService, ProfileService>();

        }

        public void Configure(IApplicationBuilder app)
        {
            if (Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // uncomment if you want to add MVC
            app.UseStaticFiles();
            app.UseRouting();

            app.UseIdentityServer();

            // uncomment, if you want to add MVC
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }
    }
}

1 Ответ

2 голосов
/ 18 июня 2020

Ну, это была 1 строка кода в моем файле startup.cs

app.UseEndpoints(endpoints =>
{
    endpoints.MapDefaultControllerRoute();
    endpoints.MapRazorPages(); // This one!
});

Да, и еще одна ошибка произошла на странице реестра, если кто-нибудь с ней столкнется.

Невозможно разрешить службу для типа Microsoft.AspNetCore.Identity.UI.Services.IEmailSender

, просто добавьте следующую строку кода в конец метода ConfigureServices в Startup.cs

services.AddTransient<IEmailSender,SomeEmailSender>();

IEmailSender из Microsoft.AspNetCore.Identity.UI.Services. Просто создайте класс, реализующий этот интерфейс, и объявите его здесь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...