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

MVC应用JWT授权失败问题:已获Token却无法完成授权

MVC中JWT授权失败的遗漏步骤

你当前的代码拿到JWT Token后未做后续处理,也未配置认证服务,导致授权失效,以下是遗漏的关键步骤:

1. 保存JWT Token到Cookie

登录成功获取Token后,需要将Token存储到Cookie中,让后续请求能带上Token供认证验证:
修改Login方法,在拿到token后添加Cookie写入逻辑:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel loginViewModel)
{
    var response = await _client.PostAsJsonAsync("Auth/Login",loginViewModel);
    if (response.IsSuccessStatusCode)
    {
        var body=await response.Content.ReadAsStringAsync();
        LoginResponse loginResponse=JsonConvert.DeserializeObject<LoginResponse>(body);
        var token = loginResponse.Token;
        
        // 新增:将Token写入Cookie
        Response.Cookies.Append("JwtToken", token, new CookieOptions
        {
            HttpOnly = true, // 提升安全性,防止前端脚本读取
            Secure = Environment.IsProduction(), // 生产环境启用HTTPS传输
            Expires = DateTime.UtcNow.AddHours(1), // 与Token的过期时间保持一致
            SameSite = SameSiteMode.Strict // 防止CSRF
        });
        
        return RedirectToAction("Index", "Dashboard");
    }
    return View("Index",loginViewModel);
}

2. 配置JWT认证服务

在Program.cs(.NET 6+)或Startup.cs中,添加JWT认证的服务配置,确保验证参数与Auth API生成Token时的参数一致:

// Program.cs示例
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "你的Auth API的Issuer", // 替换为实际的Issuer
            ValidAudience = "你的Auth API的Audience", // 替换为实际的Audience
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("你的Auth API使用的密钥")) // 替换为实际密钥
        };

        // 从Cookie中读取Token,而非默认的Authorization请求头
        options.Events = new JwtBearerEvents
        {
            OnMessageReceived = context =>
            {
                context.Token = context.Request.Cookies["JwtToken"];
                return Task.CompletedTask;
            }
        };
    });

3. 启用认证与授权中间件

在请求管道中,确保UseAuthentication在UseAuthorization之前执行,顺序不能错:

// Program.cs示例
app.UseRouting();
app.UseAuthentication(); // 必须在UseAuthorization之前
app.UseAuthorization();

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

4. (可选)指定认证方案

如果系统中有多个认证方案,需要在Dashboard控制器的[Authorize]特性中明确指定JWT方案:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class DashboardController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

内容的提问来源于stack exchange,提问作者CENGİZ Turkes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:10:31