Домашняя страница маршрута Cant после успешного входа пользователя - PullRequest
0 голосов
/ 07 ноября 2019

Я не могу направить домой / индекс после успешной регистрации из-за атрибута авторизации.

результат: https://localhost:44339/Account/Login?ReturnUrl=%2F

как я могу это исправить

в ожидании ваших ответов

// Startup.cs

public void ConfigureServices (IServiceCollection services)

{

services.AddControllersWithViews ();

        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

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

        services.AddIdentity<User, IdentityRole>()
            // services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc(op=> { op.EnableEndpointRouting = false;}).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);


        services.ConfigureApplicationCookie(options =>
        {
            options.LoginPath = $"/Account/Login";
           // options.LogoutPath = $"/Identity/Account/Logout";
            options.AccessDeniedPath = $"/Account/AccessDenied";
        });
        services.AddLogging(config =>
        {
            config.AddConsole();
            config.AddDebug();
            //etc
        });
        services.AddTransient<ClaimsPrincipal>(
             s => s.GetService<IHttpContextAccessor>().HttpContext.User);


    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider ServiceProvider ,ILoggerFactory loggerFactory)
    {
        using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.EnsureCreated();
        }
        app.UseMiddleware<RequestResponseLoggingMiddleware>();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/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.UseRouting();
        app.UseAuthorization();
        app.UseMvc();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
        loggerFactory.AddFile("Logs/ts-{Date}.txt");

        Extensions.CreateRoles(ServiceProvider).Wait();
    }

нет ошибки возврата 200

1 Ответ

0 голосов
/ 08 ноября 2019

Я не могу направить домой / индекс после успешной регистрации из-за атрибута авторизации. результат: https://localhost:44339/Account/Login?ReturnUrl=%2F

Это потому, что вы не проходите аутентификацию.

Чтобы исправить это, вам нужно добавить app.UseAuthentication(); перед app.UseAuthorization();:

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseAuthentication();

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

Ссылка: Настройка служб идентификации

ОБНОВЛЕНИЕ:

public async Task OnGetAsync(string returnUrl = null)
{
    if (!string.IsNullOrEmpty(ErrorMessage))
    {
        ModelState.AddModelError(string.Empty, ErrorMessage);
    }

    returnUrl = returnUrl ?? Url.Content("~/");

    // Clear the existing external cookie to ensure a clean login process
    await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

    ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

    ReturnUrl = returnUrl;
}

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");

    if (ModelState.IsValid)
    {
        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, set lockoutOnFailure: true
        var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
        if (result.Succeeded)
        {
            _logger.LogInformation("User logged in.");
            return LocalRedirect("/Home/Index");
        }
        if (result.RequiresTwoFactor)
        {
            return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning("User account locked out.");
            return RedirectToPage("./Lockout");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return Page();
        }
    }

        // If we got this far, something failed, redisplay form
        return Page();
}
...