简体   繁体   English

.net 核心身份“IsSignedIn”始终返回 false,即使在成功登录后

[英].net core identity 'IsSignedIn' always returns false, even after successful login

I have a .net core 3 identity project that I'm having issues with authentication.我有一个 .net core 3 身份项目,但我遇到了身份验证问题。

Login.cshtml.cs登录.cshtml.cs

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

    if (ModelState.IsValid)
    {
        // Modified base identity to allow login by email or username
        var user = await _userManager.FindByNameAsync(Input.Username);

        if (user == null)
        {
            user = await _userManager.FindByEmailAsync(Input.Username);
        }

        var result = await _signInManager.PasswordSignInAsync(user, Input.Password, Input.RememberMe, lockoutOnFailure: true);

        if (result.Succeeded)
        {
            return LocalRedirect(returnUrl);
        }

        if (result.IsNotAllowed)
        {
            return RedirectToPage("./ConfirmEmail");
        }

        if (result.IsLockedOut)
        {
            return RedirectToPage("./Lockout");
        }

        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
        return Page();
    }

    return Page();
}

From the Login page, this line of code: var result = await _signInManager.PasswordSignInAsync(user, Input.Password, Input.RememberMe, lockoutOnFailure: true);Login页面,这行代码: var result = await _signInManager.PasswordSignInAsync(user, Input.Password, Input.RememberMe, lockoutOnFailure: true); returns result.Succeeded , but from the page view, this code always returns false :返回result.Succeeded ,但从页面视图来看,此代码始终返回false

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
}

When I step through the code for the IsSignedIn method from the code below, it is failing because principal.Identities.AuthenticationType is always null .当我从下面的代码中逐步执行IsSignedIn方法的代码时,它失败了,因为principal.Identities.AuthenticationType总是null

SignInManager.cs登录管理器

public override bool IsSignedIn(ClaimsPrincipal principal)
{
    if (principal == null)
    {
        throw new ArgumentNullException(nameof(principal));
    }
    return principal?.Identities != null &&
       principal.Identities.Any(i => i.AuthenticationType == IdentityConstants.ApplicationScheme);

} }

My first thought is this is a configuration issue in Startup.cs , but I'm not sure what or where the AuthenticationType gets set?我的第一个想法是这是Startup.cs的配置问题,但我不确定AuthenticationType设置了什么或在哪里设置?

Startup.cs启动文件

    public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IDbConnection>((sp) => new SqlConnection(Configuration.GetConnectionString("Database")));
    services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddDefaultTokenProviders();
        services.ConfigureApplicationCookie(options =>
        {
            options.AccessDeniedPath ="/Account/AccessDenied";
            options.Cookie.Name = "MyApp";
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
            options.LoginPath = "/Account/Login";
            // ReturnUrlParameter requires 
            //using Microsoft.AspNetCore.Authentication.Cookies;
            options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
            options.SlidingExpiration = true;
        });
    services.AddMemoryCache();
    services.AddMvc(options => { options.EnableEndpointRouting = false; });
    services.AddRazorPages();
    services.AddSession();
    services.AddTransient<IUserStore<ApplicationUser>, CustomUserStore>();
    services.AddTransient<IRoleStore<ApplicationRole>, CustomRoleStore>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddSerilog();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

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

    app.UseAuthentication();
    app.UseAuthorization();
    app.UseSession();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapRazorPages();
    });
}

app.UseMvcWithDefaultRoute() is required to be placed after app.UseAuthentication() . app.UseMvcWithDefaultRoute()需要放在app.UseAuthentication()

Since you have used app.UseMvc() in your Configure method , just remove app.UseMvcWithDefaultRoute();由于您在Configure方法中使用了app.UseMvc() ,只需删除app.UseMvcWithDefaultRoute(); line or place it after app.UseAuthentication() in your code could resolve it.行或将其放在代码中的app.UseAuthentication()之后可以解决它。

暂无
暂无

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

相关问题 ASP.NET Core 2.0标识:SignInManager.IsSignedIn(User)在登录后返回false - ASP.NET Core 2.0 Identity: SignInManager.IsSignedIn(User) returns false after signing in 即使在使用asp.net core 2.2中的PasswordSignInAsync成功登录后,User.Identity.IsAuthenticated也始终返回false - User.Identity.IsAuthenticated always returns false even after successfully logged in using PasswordSignInAsync in asp.net core 2.2 在 asp.net 核心成功登录后,User.Identity.IsAuthenticated 在非身份验证方法中为 false - User.Identity.IsAuthenticated is false in a non-auth methods after successful login in asp.net core SignInManager.IsSignedIn(User) 方法总是返回 false - SignInManager.IsSignedIn(User) method always returns false 登录成功后传递用户详细信息来自身份asp.net core 3.1 - Pass user detail after Login Is successful From identity asp.net core 3.1 成功注册/登录后不显示注销按钮,ASP.NET Core 标识 - LOGOUT button not showing after successful REGISTER/LOGIN, ASP.NET Core Identity 登录成功后 User.Identity.IsAuthenticated 为 false - User.Identity.IsAuthenticated is false after successful login Asp.Net 核心身份 - UserManager.Users.Any() 总是返回 false - Asp.Net core identity - UserManager.Users.Any() returns always false 在.Net Core中测试一个控制器总是返回false? - Test a controller in .Net Core always returns false? 尽管成功登录,ASP.NET表单身份验证始终为false - ASP.NET Forms Authentication always false despite successful login
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM