【问题标题】:How to authorize requests with x-auth-token in its header using asp.net core api?如何使用 asp.net core api 在其标头中授权带有 x-auth-token 的请求?
【发布时间】:2019-11-17 14:33:01
【问题描述】:

我使用 asp.net core web api 生成了包含用户信息和她的角色的令牌,并在客户端获取它,然后将它放在请求标头中的 x-auth-token 中。我如何在 asp.net api 控制器和操作中授权用户(及其角色)?我在 startup.cs 中的设置如下所示,但我无法在我的操作中捕获请求!

var securityKey = Environment.GetEnvironmentVariable("SECURITY_KEY");
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
      options.TokenValidationParameters = new TokenValidationParameters()
              {
               ValidateIssuer = true,
               ValidateAudience = true,
               ValidateIssuerSigningKey = true,

               ValidIssuer = "shoniz.com",
               ValidAudience = "readers",
               IssuerSigningKey = symmetricSecurityKey
              };
    });

【问题讨论】:

    标签: authentication jwt authorization asp.net-core-webapi


    【解决方案1】:

    您示例中的代码是身份验证设置(JWT 方案)。首先,您必须添加中间件,该中间件将对用户进行身份验证。这部分代码应该出现在Startup.csConfigure()方法)中。

    app.UseAuthentication();
    

    一旦调用了这个中间件,所有的身份验证方案都会被考虑在内。当身份验证成功时,HttpContext.User 将被设置(包括您所有的问题声明)。

    第二部分是授权。 最简单的方法是使用[Authorize] 属性,您可以将其与您的操作方法和控制器一起用作注释。您可以添加自定义角色名称或策略限制。

    [Authorize(Roles = "admin")]
    public class CmsControllerBase : Controller
    {
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-17
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      相关资源
      最近更新 更多