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

如何解决ASP.NET中使用[Authorize]标记时的认证错误

问题修复方案

错误原因

出现该错误是因为两个核心问题:

  • 调用AddAuthentication()时未指定默认认证方案,导致授权流程找不到要使用的认证方式
  • Configure方法中缺少UseAuthentication()中间件,且该中间件必须在UseAuthorization()之前执行

具体修复步骤

1. 修正Startup.cs的ConfigureServices方法

在AddAuthentication中明确指定默认认证方案为你定义的Cookie方案名MyCookieAuth:

public void ConfigureServices(IServiceCollection services)
{
    // 指定默认认证方案为自定义Cookie方案
    services.AddAuthentication("MyCookieAuth")
        .AddCookie("MyCookieAuth", options =>
        {
            options.Cookie.Name = "MyCookieAuth";
            options.LoginPath = "/Account/Login";
            // 可选:保留原请求地址,登录后自动跳转回去
            options.ReturnUrlParameter = "ReturnUrl";
        });
    services.AddRazorPages();
}

2. 修正Startup.cs的Configure方法

添加app.UseAuthentication()中间件,且必须放在app.UseAuthorization()之前:

public void Configure(WebApplication app, IWebHostEnvironment env)
{
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    // 认证中间件必须在授权中间件之前执行
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapRazorPages();
    app.Run();
}

3. 完善登录页面逻辑

确保你已创建/Account/Login Razor页面,并在其后台代码中实现登录认证逻辑,示例如下:

// Login.cshtml.cs示例代码
public async Task<IActionResult> OnPostAsync(string username, string password)
{
    // 替换为你的真实用户验证逻辑
    if (ValidateUser(username, password))
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, username)
        };
        var identity = new ClaimsIdentity(claims, "MyCookieAuth");
        // 生成认证Cookie
        await HttpContext.SignInAsync("MyCookieAuth", new ClaimsPrincipal(identity));
        // 跳转回用户最初请求的页面(如果存在)
        return Redirect(Request.Query["ReturnUrl"] ?? "/");
    }
    ModelState.AddModelError("", "用户名或密码错误");
    return Page();
}

// 模拟用户验证方法
private bool ValidateUser(string username, string password)
{
    // 这里替换为数据库查询或其他验证逻辑
    return username == "admin" && password == "123456";
}

验证效果

修改完成后,访问Index页面时系统会自动跳转至/Account/Login页面,用户登录成功后将自动返回Index页面。

内容的提问来源于stack exchange,提问作者Manatchanok Bumrungban

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:22:44