繁体   English   中英

将不记名令牌发送到端点,然后验证此令牌

[英]Sending a bearer token to endpoint, then validate this token

如果我有一个将一些数据发送到端点的方法,我知道我应该使用不记名令牌来验证这个调用,在请求的标头中发送。

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

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 keyvault 中)发送到端点。
  • 从端点验证此令牌

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

发送不记名令牌就像将 HTTP 标头添加到表单的请求中一样简单: Authorization: Bearer YOURTOKEN 你可以在 C# 中这样做:

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

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

通常服务器通过检查他们的签名来验证传入的令牌。 这个检查需要知道一个秘密。 Azure KeyVault 是您可以存储该机密的地方。

通常,您使用令牌验证一次(而不是每个端点)配置您的服务器框架。 然后,您只需指明哪些端点需要令牌验证。

有许多指南可以贯穿整个过程。 这里有几个:

https://blogs.msdn.microsoft.com/webdev/2016/10/27/bearer-token-authentication-in-asp-net-core/ https://goblincoding.com/2016/07/03/issuing- and-authenticating-jwt-tokens-in-asp-net-core-webapi-part-i/

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

如果您使用 .Net Core,请查看以下库:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM