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

携带JWT的POST请求始终返回Unauthorized问题求助

JWT授权调用异常排查问题

问题描述

  • Postman和Swagger中调用接口(如Authenticate、GetUser)均能成功,但自行编写的C#代码(包括RestSharp调用)始终返回Unauthorized响应
  • 已确认Token有效,尝试过ChatGPT的建议但问题依旧

WebAPI代码

Program.cs(JWT配置)

// JWT configuration
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        //options.RequireHttpsMetadata = false;
        //options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "your_issuer",
            ValidAudience = "your_audience",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("e91ec378-3c0f-4a32-98d1-573f158eb12a"))
        };
    });
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy(IdentityData.AdminPolicyName, policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim(IdentityData.AdminUserClaimName, "ADMN");
    });
});

//....

app.UseAuthentication();
app.UseAuthorization();

Controller代码

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    [Authorize]
    [HttpPost("Authenticate")]
    [ProducesResponseType(typeof(ReturnObject), (int)HttpStatusCode.OK)]
    public ActionResult<ReturnObject> Authenticate([FromBody] RequestObject body)
    {
    }
}

JWT生成代码

[AllowAnonymous]
[HttpPost("GenerateToken")]
public IActionResult GenerateToken([FromBody] IdentityClaims request)
{
    var claims = new[]
    {
        new Claim(ClaimTypes.Name, request.Username),
        new Claim(ClaimTypes.Email, request.Email),
        new Claim("Role", request.Role)
    };

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("e91ec378-3c0f-4a32-98d1-573f158eb12a"));
    var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    var token = new JwtSecurityToken(
        issuer: "your_issuer",
        audience: "your_audience",
        claims: claims,
        expires: DateTime.Now.AddDays(1),
        signingCredentials: credentials
    );

    var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

    return Ok(new { Token = tokenString });
}

补充说明

GetUser接口存在同样问题:代码调用返回Unauthorized,但Postman和Swagger中可正常执行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 06:35:08