You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署.NET Core 7.0 Identity库后网站无法登录的解决咨询

.NET Core 7.0 Identity登录失败问题排查与解决

问题背景

使用.NET Core 7.0 Identity开发的网站上线后,访问即跳转至登录页面,输入正确账号密码后仍无法完成登录,相关配置代码如下:

builder.Services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});

builder.Services.AddMvc();

builder.Services.ConfigureApplicationCookie(options =>
{
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(100);
    options.AccessDeniedPath= "/ErrorPage/Index";
    options.LoginPath = "/Writer/Login/Index";
});

核心问题与修复步骤

1. 移除重复Mvc注册,避免配置覆盖

连续调用两次builder.Services.AddMvc()会导致第一次添加的全局授权过滤器被重置覆盖,直接删除冗余的builder.Services.AddMvc();即可。

2. 避免登录页面被全局授权拦截

全局配置的RequireAuthenticatedUser策略会强制所有请求需要已认证用户,包括登录页面本身,形成"访问跳登录→登录页要求认证"的死循环,导致登录后仍无法正常访问。

解决方式二选一:

  • 在登录页面的Controller或Action上添加[AllowAnonymous]特性:
    [AllowAnonymous]
    public class LoginController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
    
  • 或者在全局授权配置中排除登录路径:
    builder.Services.AddMvc(config =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
        // 允许登录路径匿名访问
        config.Filters.Add(new AllowAnonymousFilter { Paths = { "/Writer/Login/Index" } });
    });
    

3. 检查Cookie配置与登录逻辑

  • 生产环境HTTPS适配:如果网站使用HTTPS,需开启Cookie的Secure属性,否则Cookie无法被正确保存:
    builder.Services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // HTTPS环境下启用
        options.ExpireTimeSpan = TimeSpan.FromMinutes(100);
        options.AccessDeniedPath= "/ErrorPage/Index";
        options.LoginPath = "/Writer/Login/Index";
        options.ReturnUrlParameter = "ReturnUrl"; // 确保跳转参数正常传递
    });
    
  • 登录逻辑校验:确认登录Action中正确调用Identity的登录方法,并在成功后执行正确跳转:
    public async Task<IActionResult> Index(LoginModel model)
    {
        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                // 跳转至原请求页面或首页
                return Redirect(model.ReturnUrl ?? "/Home/Index");
            }
            ModelState.AddModelError("", "用户名或密码错误");
        }
        return View(model);
    }
    

4. 确保中间件顺序正确

在Program.cs中,中间件必须按以下顺序配置,否则认证信息无法被正确识别:

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

app.UseRouting();

// 先执行认证,再执行授权
app.UseAuthentication();
app.UseAuthorization();

// 最后配置路由
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

内容的提问来源于stack exchange,提问作者Burcu Ustael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:27:52