首页 > 解决方案 > PasswordSignIn 返回成功,但重定向到另一个 ActionResult 用户未在 net core 3.1 中进行身份验证

问题描述

我使用 net core 3.1 和 EF core 进行身份验证和登录。首先,我使用 passwordSignIn 方法登录并返回成功,然后我将 retdirectToAction 设置为“配置文件”。

在“个人资料”中,User.Identity.isAuthenticated 为假。

正如您在我的代码中看到的那样,我设置了登录完成并且工作正常。但用户未通过身份验证。这是我的登录信息:

[HttpPost]
    public async Task<IActionResult> SignUp(string username, string password)
    {
        var user = _db.Users.Where(p => p.UserName == username).FirstOrDefault();
        if (user != null)
        {
            var res = await _signInManager.PasswordSignInAsync(user, password, true, false);
            if (res.Succeeded)
            {

                return RedirectToAction("profile");


            }

        }


        return View();
    }

这是个人资料:

public IActionResult Profile()
    {
        var t = User.Identity.IsAuthenticated;
        var n = User.Identity.Name;
        var s = User.Claims.ToList();
        var x = _userManager.GetUserId(User);

        var ss = User.IsInRole("Admin");
        return View();
    }

这是我的启动:

public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddControllersWithViews();

        services.AddDbContext<MyContext>(opt =>
        {
            opt.UseSqlServer(Encryptor.Decrypt(Configuration.GetConnectionString("DefaultConnection")));
        });

        var builder = services.AddIdentityCore<User>();
        var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);
        identityBuilder.AddRoles<UserRole>();
        identityBuilder.AddEntityFrameworkStores<MyContext>();
        identityBuilder.AddSignInManager<SignInManager<User>>();
        services.ConfigureApplicationCookie(options =>
        {

            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            options.LoginPath = "/Account/Login";
            options.AccessDeniedPath = "/Account/AccessDenied";
            options.SlidingExpiration = true;
        });
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie("Identity.Application");
    }
 
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();


        app.UseRouting();
        app.UseAuthentication();

        app.UseAuthorization();

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

更新启动

public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllersWithViews();

        services.AddDbContext<MyContext>(opt =>
        {
            opt.UseSqlServer(Encryptor.Decrypt(Configuration.GetConnectionString("DefaultConnection")));
        });

        var builder = services.AddIdentityCore<AppUser>();
        var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);
        identityBuilder.AddRoles<Role>();
        identityBuilder.AddEntityFrameworkStores<MyContext>().AddDefaultTokenProviders();
        identityBuilder.AddSignInManager<SignInManager<AppUser>>();

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.ConsentCookie.IsEssential = true;
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.Configure<IdentityOptions>(options =>
        {
            options.SignIn.RequireConfirmedEmail = false;
            options.SignIn.RequireConfirmedAccount = false;
            options.SignIn.RequireConfirmedPhoneNumber = false;
        });
        

      


        
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie("Identity.Application");
    
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }



        app.UseStaticFiles();


        app.UseRouting();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "Admin",
                pattern: "{area:exists}/{controller=Admin}/{action=Index}/{id?}");
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

标签: asp.net-coreentity-framework-coreasp.net-identityidentityasp.net-core-3.1

解决方案


最后我在@Yinqiu的帮助下解决了问题并进行了更多搜索。我将这些行添加到登录方法:

    var claims = new[] 
{ 
    new Claim("name", authUser.Username)
};

    var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

我不知道它是如何解决的,但它确实有效。

当然,我在启动课上换行:

... .AddCookie("Cookie");

推荐阅读