如何使用 asp.net core api 在其标头中授权带有 x-auth-token 的请求?

Posted

技术标签:

【中文标题】如何使用 asp.net core api 在其标头中授权带有 x-auth-token 的请求?【英文标题】:How to authorize requests with x-auth-token in its header using asp.net core api? 【发布时间】: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
              ;
    );

【问题讨论】:

【参考方案1】:

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

app.UseAuthentication();

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

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

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


【讨论】:

以上是关于如何使用 asp.net core api 在其标头中授权带有 x-auth-token 的请求?的主要内容,如果未能解决你的问题,请参考以下文章