ASP.NETWebAPI授权被拒绝,即使令牌并未过期,怎么解决?需要提供示例代码。
创始人
2024-09-19 13:30:22
0

可能的原因是令牌不包含所需要的授权信息,或者在 API 控制器中没有正确配置身份验证和授权。首先,确认要访问的 API 是否需要身份验证和授权,然后使用适当的方法生成令牌并将其添加到请求头中。以下是一个简单的示例代码:

  1. 在 Startup.cs 中配置身份验证和授权
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["Jwt:Issuer"],
                ValidAudience = Configuration["Jwt:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
            };
        });

    services.AddAuthorization(options =>
    {
        options.AddPolicy("AuthorizedUsersOnly", policy => policy.RequireRole("Administrator", "Operator"));
    });

    services.AddControllers();
}
  1. 在控制器中添加授权属性
[Authorize(Roles = "Administrator")]
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
    // API methods
}
  1. 发送请求时添加令牌
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await client.GetAsync("http://localhost:5000/api/users");

通过这些步骤,应该可以解决 ASP.NET Web API 授权被拒绝的问题。

相关内容

热门资讯

透视系统(wopoker)外挂... 透视系统(wopoker)外挂透明挂辅助器(wepoke辅助技巧)其实有挂(详细透视安装教程);小薇...
透视代打(德州微扑克辅助)微扑... 透视代打(德州微扑克辅助)微扑克真的有外挂嘛(详细辅助细节揭秘)竟然真的有挂;人气非常高,ai更新快...
透视软件(wpk俱乐部)wpk... 透视软件(wpk俱乐部)wpk发牌规律(详细辅助必赢教程)竟然真的有挂;是一款可以让一直输的玩家,快...
透视科技(WEpoke)透明挂... 透视科技(WEpoke)透明挂辅助器(wepoke有没有挂)固有存在有挂(详细透视技巧教程);小薇(...
透视科技(wopoker)透视... 透视科技(wopoker)透视辅助插件(wepoke真的有挂)起初是真的有挂(详细透视必备教程);实...
透视存在(wepoke真的有挂... 自定义wepoke真的有挂系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,...
透视黑科技(德州ai辅助软件)... 透视黑科技(德州ai辅助软件)wepoke系统规律(详细辅助安装教程)竟然有挂;小薇(透视辅助)致您...
透视安装(wePOKE)透明挂... 透视安装(wePOKE)透明挂辅助代打(wepoke辅助德之星)一向是真的有挂(详细透视新2025版...
透视神器(wEpOke)透视辅... 透视神器(wEpOke)透视辅助挂(wepokeai辅助)切实是真的有挂(详细透视力荐教程);科技安...
透视有挂(aapoker发牌机... 透视有挂(aapoker发牌机制)wopoker用ai有用吗(详细辅助安装教程)总是存在有挂;透视有...