2017-02-13 84 views
1

如果我有一個方法發送一些數據到端點,我知道我應該使用一個不記名的令牌來認證這個調用,並在請求的頭部發送。發送一個不記名令牌給端點,然後驗證這個令牌

說我的方法是向/從端點接收數據/看起來像這樣:

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); 
     } 

怎麼辦I:

  • 發送無記名令牌(自定義存儲在azure keyvault中)到端點。
  • 驗證此令牌從端點

我無法找到這樣做的任何初學者友好的文檔。

回答

1

發送不記名令牌就像向表單的請求添加HTTP標頭一樣簡單:Authorization: Bearer YOURTOKEN。您可以在C#中這樣做:

using (var client = new HttpClient()) 
    { 
    httpClient.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/

如果這還不夠,那麼你應該張貼關於您的使用情況下,你知道什麼更具體的信息。