Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net core PasswordSignIn返回成功,但重定向到另一个ActionResult后,net core 3.1中未对用户进行身份验证_Asp.net Core_Entity Framework Core_Asp.net Identity_Identity_Asp.net Core 3.1 - Fatal编程技术网

Asp.net core PasswordSignIn返回成功,但重定向到另一个ActionResult后,net core 3.1中未对用户进行身份验证

Asp.net core PasswordSignIn返回成功,但重定向到另一个ActionResult后,net core 3.1中未对用户进行身份验证,asp.net-core,entity-framework-core,asp.net-identity,identity,asp.net-core-3.1,Asp.net Core,Entity Framework Core,Asp.net Identity,Identity,Asp.net Core 3.1,我使用用户NETCore3.1和EFCore进行身份验证和登录。 首先,我使用passwordSignIn方法进行签名并返回Successful,然后将DirectToAction返回到“profile” 在“配置文件”中,User.Identity.isAuthenticated为false 正如您在我的代码中所看到的,我设置了完整的登录,并且工作正常。但用户未经过身份验证。 这是我的登录: [HttpPost] public async Task<IActionResult&g

我使用用户NETCore3.1和EFCore进行身份验证和登录。 首先,我使用passwordSignIn方法进行签名并返回Successful,然后将DirectToAction返回到“profile”

在“配置文件”中,User.Identity.isAuthenticated为false

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

[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 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?}");
        });
    }
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。使用此方法向容器中添加服务。
public void配置服务(IServiceCollection服务)
{
配置(选项=>
{
//此lambda确定给定请求是否需要非必要cookie的用户同意。
options.checkApprovered=context=>true;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
services.AddControllersWithViews();
services.AddDbContext(opt=>
{
opt.UseSqlServer(Encryptor.Decrypt(Configuration.GetConnectionString(“DefaultConnection”));
});
var builder=services.AddIdentityCore();
var identityBuilder=新identityBuilder(builder.UserType,builder.Services);
identityBuilder.AddRoles();
identityBuilder.AddEntityFrameworkStores();
identityBuilder.AddSignInManager();
services.configureApplicationOK(选项=>
{
options.Cookie.HttpOnly=true;
options.ExpireTimeSpan=TimeSpan.FromMinutes(30);
options.LoginPath=“/Account/Login”;
options.AccessDeniedPath=“/Account/AccessDenied”;
options.SlidingExpiration=true;
});
AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(“Identity.Application”);
}
//此方法由运行时调用。使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllerRoute(
名称:“管理员”,
模式:“{area:exists}/{controller=Admin}/{action=Index}/{id?}”);
endpoints.MapControllerRoute(
名称:“默认”,
模式:“{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?}");
        });
    }
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。使用此方法向容器中添加服务。
public void配置服务(IServiceCollection服务)
{
services.AddControllersWithViews();
services.AddDbContext(opt=>
{
opt.UseSqlServer(Encryptor.Decrypt(Configuration.GetConnectionString(“DefaultConnection”));
});
var builder=services.AddIdentityCore();
var identityBuilder=新identityBuilder(builder.UserType,builder.Services);
identityBuilder.AddRoles();
identityBuilder.AddEntityFrameworkStores().AddDefaultTokenProviders();
identityBuilder.AddSignInManager();
配置(选项=>
{
//此lambda确定给定请求是否需要非必要cookie的用户同意。
options.approvementCookie.IsEssential=true;
options.checkApprovered=context=>true;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
配置(选项=>
{
options.SignIn.RequireConfirmedEmail=false;
options.SignIn.RequireConfirmedAccount=false;
options.SignIn.RequireConfirmedPhoneNumber=false;
});
AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(“Identity.Application”);
services.AddMvc();
}
//此方法由运行时调用。使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseStaticFiles();
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllerRoute(
名称:“管理员”,
模式:“{area:exists}/{controller=Admin}/{action=Index}/{id?}”);
endpoints.MapControllerRoute(
名称:“默认”,
模式:“{controller=Home}/{action=Index}/{id?}”);
});
}

最后,我在搜索的帮助下解决了这个问题。 我将这些行添加到signin方法:

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

    var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
我不知道它是如何解决的,但它是有效的

当然,我在创业课上换了一行:

... .AddCookie("Cookie");

我在stackoverflow中检查解决方案,但我都检查了。启动可能有问题?请尝试在操作方法上显式应用
[授权(AuthenticationSchemes=CookieAuthenticationDefaults.AuthenticationScheme)]
以指定要使用的身份验证方案,然后检查它是否
... .AddCookie("Cookie");