簡體   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