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

.NET Core登录后无法访问[Authorize]授权页面问题求助

.NET Core中登录后无法访问带[Authorize]特性页面的排查与解决

问题现象

登录成功后可跳转至指定页面,但访问标记了[Authorize]特性的/user/settings页面时,被强制重定向到登录页(URL:https://localhost:61378/home/index?ReturnUrl=%2Fuser%2Fsettings),无法正常进入授权页面。已完成Cookie认证服务注册、登录Post接口开发及前端AJAX登录逻辑实现。


核心排查与修复方案

1. 认证中间件顺序错误(最可能的原因)

仅注册认证服务但未启用认证/授权中间件,或中间件顺序错误,会导致授权系统无法识别已登录身份。

问题代码(Program.cs):

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/home/index";
    });

修复:

在app.MapControllers()/app.MapRazorPages()之前按顺序添加中间件:

// 先启用认证(必须在授权之前)
app.UseAuthentication();
// 再启用授权
app.UseAuthorization();

2. TempData获取ReturnUrl无效

AJAX登录场景下,TempData无法跨请求传递(AJAX请求与页面跳转是独立请求),导致ReturnUrl为空,可能干扰认证上下文的持久化逻辑。

问题代码片段(登录接口):

authProperties = new AuthenticationProperties
{
    RedirectUri = TempData["ReturnUrl"]?.ToString() ?? "/admin/dashboard",
};

修复:

从请求Query参数中获取ReturnUrl,同时前端请求时主动传递该参数:

  • 后端修改:
// 新增[FromQuery]参数接收ReturnUrl
public async Task<IActionResult> Login([FromBody] LoginViewModel formData, [FromQuery] string returnUrl)
{
    // ...其他逻辑
    if (LogedIn.IsAdmin == true)
    {
        authProperties = new AuthenticationProperties
        {
            RedirectUri = !string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) 
                ? returnUrl 
                : "/admin/dashboard",
        };
    }
    else
    {
        authProperties = new AuthenticationProperties
        {
            RedirectUri = !string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) 
                ? returnUrl 
                : "/dashboard/dashboard",
        };
    }
    // ...其他逻辑
}
  • 前端修改:
// 获取当前URL中的ReturnUrl参数并传递给登录接口
const returnUrl = new URLSearchParams(window.location.search).get('ReturnUrl');
var URL = "/User/Login" + (returnUrl ? `?returnUrl=${encodeURIComponent(returnUrl)}` : "");

3. 认证Cookie配置不兼容HTTPS环境

HTTPS环境下未开启Cookie的Secure属性,或SameSite配置不当,会导致Cookie无法在跨请求时传递。

修复(Program.cs):

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/home/index";
        // HTTPS环境强制启用Secure
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        // 适配AJAX与页面跳转的SameSite规则
        options.Cookie.SameSite = SameSiteMode.Lax;
        // 可选:设置Cookie有效期
        options.ExpireTimeSpan = TimeSpan.FromHours(8);
    });

4. Session配置缺失(可选)

登录接口依赖Session存储UserId,但如果未正确配置Session服务与中间件,可能间接影响认证上下文。

修复(Program.cs):

// 注册Session服务
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromHours(8);
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.Cookie.SameSite = SameSiteMode.Lax;
});

// 启用Session(需在认证中间件之前)
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();

5. 授权页面依赖Session而非认证上下文

授权页面通过Session获取UserId,而非从认证Claims中提取,依赖Session状态而非认证系统本身,存在身份校验漏洞。

修复(授权页面代码):

[Authorize]
public async Task<IActionResult> settings()
{
    try
    {
        // 从认证Claims中直接获取用户ID,无需依赖Session
        var userId = User.FindFirstValue(ClaimTypes.Name);
        if (!string.IsNullOrEmpty(userId))
        {
            var Userroot = await webApiService.GetAsync<UserRootModel>(Constants.GetUser + userId);
            if (Userroot != null)
            {
                return View(Userroot.User);
            }
            else
            {
                return Json(new { message = "获取用户信息失败,请重试。" }); 
            }
        }
        else
        {
            return Json(new { message = "用户身份验证失败,请重试。" });
        }
    }
    catch (Exception ex)
    {
        return Json(new { message = "系统异常,请重试。" });
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:25:25