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

ASP.NET Core 6 JWT认证浏览器报401未授权,Postman正常

JwtBearer认证:浏览器页面跳转返回401未授权,但Postman/AJAX正常

我用JwtBearer实现了一个简单的认证系统,Postman中能正常获取Token并访问带[Authorize]特性的接口,但浏览器页面跳转时一直收到401未授权错误。AJAX请求手动携带Authorization: 'Bearer ' + jwt头时可以正常访问,说明问题出在页面跳转时没传递JWT Token。

相关配置与代码

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Jwt": {
    "Issuer": "https://localhost:5165/",
    "Audience": "https://localhost:5165/",
    "Key": "topsecrettoken"
  },
  "AllowedHosts": "*"
}

Program.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
    .AddJwtBearer(options =>
    {
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
            ValidateIssuer = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidateAudience = true,
            ValidAudience = builder.Configuration["Jwt:Audience"]
        };
    });

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();

app.MapControllers();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Path}/{action=Index}");

app.Run();

GenerateJsonWebToken方法

private string GenerateJsonWebToken(UserModel user)
{
    var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_config["Jwt:Key"]));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha512Signature);

    var claims = new[]
    {
        new Claim(ClaimTypes.NameIdentifier, user.UserName!),
        new Claim(ClaimTypes.Email, user.Email!),
        new Claim(ClaimTypes.GivenName, user.FirstName!),
        new Claim(ClaimTypes.Surname, user.LastName!),
        new Claim(ClaimTypes.Role, user.Role!)
    };

    var token = new JwtSecurityToken(
        _config["Jwt:Issuer"],
        _config["Jwt:Audience"],
        claims,
        expires: DateTime.Now.AddHours(1),
        signingCredentials: credentials
    );

    return new JwtSecurityTokenHandler().WriteToken(token);
}

受限测试接口

[HttpPost]
[Authorize]
[Route("auth")]
public IActionResult AuthTest()
{
    return Ok("Authenticated with JWT!");
}

测试结果

  • Postman:在请求头中添加Authorization: Bearer <生成的Token>,可成功访问/auth接口,返回"Authenticated with JWT!"。
  • AJAX请求:手动设置请求头Authorization: 'Bearer ' + jwt,同样能正常访问受限接口。
  • 浏览器页面跳转:直接访问带[Authorize]特性的页面路由时,返回401未授权,核心原因是页面跳转的请求中没有携带JWT Token。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 23:07:01