【问题标题】:.NET Core API keys & Identity integration.NET Core API 密钥和身份集成
【发布时间】:2020-11-16 15:05:17
【问题描述】:

目前正在使用 .NET CORE 3.1 和 Identity 构建一个 API,以在其中管理我们的身份验证/授权。我们希望使用生成的 API 密钥,而不是需要刷新的短期令牌(它不适合我们的用例场景)。

我们要做的是为用户/第三方提供生成 API 密钥的选项,并允许他们将身份角色分配给 API 密钥而不是用户。这样我们仍然可以使用 [Authorize] 属性来授予/限制他们对特定端点的访问。

我们有一个用户表来处理核心应用程序本身内的身份验证/授权,并有一个表来存储生成的 API 密钥。一个用户可以生成多个 API 密钥(例如,一个对端点具有只读权限,一个具有写入权限)。我们只需要将 API 密钥链接到身份角色,并在通过请求标头传入 API 密钥时使用 [Authorize] 属性。

有人对如何进行这项工作有任何想法/建议吗?或者关于这是否是一个坏主意以及如何做得更好的任何建议?任何建议表示赞赏。

【问题讨论】:

标签: c# asp.net-core asp.net-identity asp.net-core-webapi


【解决方案1】:

您可以覆盖许多 JWT 示例使用的 [Authorize] 属性,但它有点不合时宜的解决方案,可以让 JWT 做一些它不打算做的事情。

我的建议是将 API 密钥添加为 API 端点的请求参数,并将任何数据负载放入请求正文中。例如/api/someendpoint/?apiKey={some_api_key}

然后,您可以为 API 控制器创建一个 BaseController 类,以便在需要时对密钥执行验证检查。

这将不允许您随意使用 [Authorize] 属性,但它会让您在短期内启动并运行。一旦您掌握了主要概念,创建自定义 [AuthorizeApiKey] 属性就不会太远了,但这需要您进行调查。

这是一些示例代码。

BaseController.cs

public class BaseController : Controller
{
  ...
  // Returns true if key is valid, returns false if invalid
  protected async Task<bool> ValidateApiKey(string apiKey)
  {
    var result = false;

    // Logic to check API key...

    return result;
  }

  ...
}

SomeApiController.cs

[Area("API")]
[Route("api/[controller]")]
[ApiController]
public class SomeApiController : BaseController
{
   [HttpGet]
   public async Task<IActionResult> GetWidgets(string apiKey)
   {
      var authorized = ValidateApiKey(apiKey);
      
      // If key is invalid, return a relevant response
      if(!authorized) return Unauthorized();

      // Otherwise, process the request and return the expected result
      var widgets = _SomeWidgetService.GetWidgets();

      return Created(widgets);
   }


   [HttpPost]
   public async Task<IActionResult> CreateWidget(string apiKey, [FromBody] WidgetClass widget)
   {
      var authorized = ValidateApiKey(apiKey);
      
      // If key is invalid, return a relevant response
      if(!authorized) return Unauthorized();

      // Otherwise process the rest of the action
      var result = (bool)_SomeWidgetService.CreateWidget(widget);

      if(result)
         return Created(); 
      else
         return BadRequest();
   }
}

【讨论】:

    猜你喜欢
    • 2020-10-15
    • 2019-08-04
    • 2018-01-29
    • 2018-02-27
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多