将持有者令牌发送到终结点,然后验证此令牌



如果我有一个将一些数据发送到端点的方法,我明白我应该使用持有者令牌来验证此调用,在请求的标头中发送。

假设我向/从端点发送/接收数据的方法如下所示:

public async Task<string> PostGetAsync()
        {
            var uri = new Uri("https://localhost:44322/endpoint");
            using (var client = new HttpClient())
            {
                var pairs = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("Key", "Value")
                };
                var content = new FormUrlEncodedContent(pairs);
                var response = await client.PostAsync(uri, content);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return "Error posting KeyValue";
                }
                string responseString = response.Content.ReadAsStringAsync().Result;
                JArray json = JArray.Parse(responseString);
                try
                {
                    var returnedJson = json[returnedData];
                    return returnedJson.ToString();
                }
                catch (Exception e)
                {
                    return "Index is out of bounds";
                }
            }
        }

当该端点运行时运行的方法称为:

public async Task<JsonResult> endpoint()
        {
            List<Example> items = new List<Example>();
            NameValueCollection nvc = Request.Form;
            string keyString = nvc["Key"];
            try
            {
                items = await GetService.GetList(keyString);
            }
            catch (ServiceException se)
            {
            }
            return Json(items, JsonRequestBehavior.AllowGet);
        }

如何:

  • 将持有者令牌(自定义存储在 Azure 密钥保管库中(发送到终结点。
  • 从终结点验证此令牌

我找不到任何适合初学者的文档来执行此操作。

发送持有者令牌就像将 HTTP 标头添加到以下形式的请求中一样简单:Authorization: Bearer YOURTOKEN 。 你可以在 C# 中做到这一点,如下所示:

using (var client = new HttpClient())
  {
    client.DefaultRequestHeaders.Authorization =
      new AuthenticationHeaderValue("Bearer", yourTokenString);
    // .. rest of your code

对于服务器终结点,您非常不清楚您希望如何验证令牌。 你提到了 Azure KeyVault,但没有说明你使用它的用途。

通常,服务器通过检查传入令牌的签名来验证传入令牌。 此检查需要知道机密。 Azure 密钥保管库是可以存储该机密的位置。

通常,使用令牌验证配置服务器框架一次(而不是按端点(。 然后,只需指示哪些终结点需要令牌验证。

有许多指南涵盖了整个过程。 这里有一对:

https://blogs.msdn.microsoft.com/webdev/2016/10/27/bearer-token-authentication-in-asp-net-core/

如果这还不够,那么您应该发布有关您的用例和您所知道的更具体的信息。

如果你在 .Net Core 中,请查看以下库:

  1. 服务器端:https://identityserver4.readthedocs.io/en/latest/。在这里,您将找到有关如何配置身份验证服务的非常详细的描述,该服务将在身份验证后生成令牌。
  2. 客户端:https://identitymodel.readthedocs.io/en/latest/。在这里,您将找到处理所有客户端问题的框架,例如获取令牌,请求中的注入,自动续订...从字面上看,几行配置,您将所有令牌管理抽象到身份模型框架中。

相关内容

最新更新