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

ASP.NET Core 6 ReactJS模板控制器用户获取失败且Authorize无效

问题分析与解决方案

核心原因

ASP.NET Core 6 React模板默认的Cookie认证配置主要适配MVC页面场景,API控制器需额外配置才能正确识别用户身份;同时前端调用API时若未正确传递认证凭证,会导致[Authorize]特性失效、无法获取用户信息。


步骤1:修正Program.cs的认证与CORS配置

确保认证中间件正确配置,且CORS允许传递凭证:

var builder = WebApplication.CreateBuilder(args);

// 模板原有数据库与身份服务配置
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

// 关键:为API配置Cookie认证方案
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.Cookie.SameSite = SameSiteMode.Lax;
        options.Events = new CookieAuthenticationEvents
        {
            OnRedirectToLogin = context =>
            {
                // API请求返回401而非跳转登录页面
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                return Task.CompletedTask;
            }
        };
    });

// 配置CORS允许凭证(适配前后端跨域场景)
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowReactApp", policy =>
    {
        policy.WithOrigins("https://localhost:3000") // 替换为你的React实际运行端口
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials(); // 必须开启才能传递认证Cookie
    });
});

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

var app = builder.Build();

// 中间件顺序必须遵循:CORS → 认证 → 授权
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors("AllowReactApp");
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");
app.MapRazorPages();
app.MapFallbackToFile("index.html");

app.Run();

步骤2:修正前端API调用代码

确保React调用API时携带认证凭证:

  • 使用fetch时添加credentials: 'include':
fetch('/api/MyController', {
  credentials: 'include'
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('请求错误:', error));
  • 使用axios时配置全局默认:
axios.defaults.withCredentials = true;

步骤3:修复控制器代码错误

你的Get方法使用了await但未标记为async,修正后即可正常获取用户信息:

[HttpGet]
public async Task<IEnumerable<Something>> Get()
{
    var userName = User.Identity?.Name;
    var currentUser = await _userManager.GetUserAsync(User);
    var userId = currentUser?.Id;

    // 业务逻辑实现...
    return new List<Something>();
}

验证要点

  • 检查浏览器请求API时,Request Headers是否包含Cookie字段,且存在.AspNetCore.Identity.Application Cookie
  • 确认User.Identity.IsAuthenticated返回true
  • 验证未登录请求API时返回401,登录后可正常获取用户信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:40:28