如果我有一个将一些数据发送到端点的方法,我知道我应该使用不记名令牌来验证此调用,在请求的标头中发送。
假设我向端点发送数据/从端点接收数据的方法如下所示:
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);
}
我如何:
我找不到任何初学者友好的文档来做这个。
发送不记名令牌就像向表单请求添加 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/
如果这还不够,那么您应该发布有关您的用例和您所知道的更多具体信息。
如果您使用的是 .Net Core,请查看以下库: