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

Postman使用JWT Token调用接口返回401错误求助

问题描述

通过Swagger生成JWT Token后,在jwt.io中可正常解析,但将该Token添加到Postman中调用接口时返回401错误。以下是Token生成的C#代码:

public class TokenHandler : ITokenHandler
{
    private readonly IConfiguration _configuration;
    public TokenHandler(IConfiguration configuration)
    {
        this._configuration = configuration;
    }
    public Task<string> CreateTokenAsync(User user)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));


        // create Claims
        var claims = new List<Claim>();

        claims.Add(new Claim(ClaimTypes.GivenName, user.FirstName));
        claims.Add(new Claim(ClaimTypes.Surname, user.LastName));
        claims.Add(new Claim(ClaimTypes.Email, user.EmailAddress));


        //loop into roles of users
        user.Roles.ForEach((role) =>
        {
            claims.Add(new Claim(ClaimTypes.Role, role));
        });

        var credentials = new SigningCredentials(key,SecurityAlgorithms.HmacSha256);
        var token = new JwtSecurityToken(
            _configuration["Jwt:Issuer"],
            _configuration["Jwt:Audience"],
            claims,
            expires: DateTime.Now.AddMinutes(15),
            signingCredentials: credentials);

        return Task.FromResult(new JwtSecurityTokenHandler().WriteToken(token));
    }
}
可能的原因及排查方向
  • Token在Postman中的格式错误:确保在Postman的Authorization选项卡选择Bearer Token类型,仅粘贴Token字符串本身;若手动添加Authorization请求头,需严格写成Bearer <你的Token>,注意Bearer后必须有一个空格,避免重复添加前缀导致格式无效。
  • JWT配置参数不匹配:检查API项目配置文件(如appsettings.json)中的Jwt:Issuer、Jwt:Audience、Jwt:Key是否与生成Token时的配置完全一致:
    • Issuer或Audience不一致会导致API验证时因发行方/受众不匹配拒绝Token;
    • HmacSha256算法要求密钥至少32字节,若Jwt:Key长度不足,会直接导致签名验证失败返回401,需更换更长的密钥。
  • JWT验证中间件配置缺失或错误:确认项目的Startup/Program.cs中正确配置了JWT验证逻辑,示例如下:
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = builder.Configuration["Jwt:Issuer"],
                ValidAudience = builder.Configuration["Jwt:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
            };
        });
    
    同时要确保中间件管道中添加了app.UseAuthentication();和app.UseAuthorization();,且顺序必须是Authentication在前、Authorization在后。
  • Token已过期:虽然代码设置了15分钟有效期,但如果生成Token后间隔过久测试,或服务器与本地时间存在较大偏差,都会导致Token被判定为过期。可在jwt.io查看Token的exp字段,确认过期时间是否符合预期。
  • 接口授权策略不匹配:若接口使用了[Authorize(Roles="xxx")]或自定义Claim验证规则,而生成的Token中未包含对应的Role或Claim,会触发401。检查接口的授权属性,对比jwt.io中显示的Token Claim列表是否满足要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:30:51