简体   繁体   English

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

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

If I have a method that sends some data to an endpoint, I understand I should use a bearer token to authenticate this call, sent in the header of the request.如果我有一个将一些数据发送到端点的方法,我知道我应该使用不记名令牌来验证这个调用,在请求的标头中发送。

Say my method that sends/receives data to/from the endpoint looks like this:假设我向/从端点发送/接收数据的方法如下所示:

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

And the method that runs when that endpoint is called it this:当该端点被调用时运行的方法是:

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

How do I:我如何能:

  • Send a bearer token (custom stored in azure keyvault) to the endpoint.将不记名令牌(自定义存储在 azure keyvault 中)发送到端点。
  • Validate this token from the endpoint从端点验证此令牌

I can't find any beginner friendly docs for doing this.我找不到任何适合初学者的文档来执行此操作。

Sending a bearer token is as easy as adding an HTTP Header to the request of the form: Authorization: Bearer YOURTOKEN .发送不记名令牌就像将 HTTP 标头添加到表单的请求中一样简单: Authorization: Bearer YOURTOKEN You can do it in C# like so:你可以在 C# 中这样做:

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

For the server endpoint, you were pretty unclear how you wish to validate the token.对于服务器端点,您非常不清楚您希望如何验证令牌。 You mention Azure KeyVault but don't say what you are using it for.您提到了 Azure KeyVault,但没有说明您使用它的目的。

Usually the server validates incoming tokens by checking their signature.通常服务器通过检查他们的签名来验证传入的令牌。 This check requires knowing a secret.这个检查需要知道一个秘密。 Azure KeyVault is where you might store that secret. Azure KeyVault 是您可以存储该机密的地方。

Typically you configure your server framework with the token verification once (instead of per end point).通常,您使用令牌验证一次(而不是每个端点)配置您的服务器框架。 You then just indicate which endpoints require token verification.然后,您只需指明哪些端点需要令牌验证。

There are a number of guides that go over the whole process.有许多指南可以贯穿整个过程。 Here are a couple:这里有几个:

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/ 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/

If this isn't sufficient then you should post more specific information about your use case and what you know.如果这还不够,那么您应该发布有关您的用例和您所知道的更多具体信息。

If you are in .Net Core, look at following libraries:如果您使用 .Net Core,请查看以下库:

  1. Server Side : https://identityserver4.readthedocs.io/en/latest/ .服务器端https : //identityserver4.readthedocs.io/en/latest/ Here you will find very detailed description how to configure your authentication service, service which will produce tokens, after authentication.在这里您将找到非常详细的描述如何配置您的身份验证服务,该服务将在身份验证后生成令牌。
  2. Client side : https://identitymodel.readthedocs.io/en/latest/ .客户端https : //identitymodel.readthedocs.io/en/latest/ Here you will find framework which handles all client side troubles, like fetching token, injections in request, automatic renewals... Literally few lines of configuration, and you abstract all token management to identitymodel framework..在这里,您将找到处理所有客户端问题的框架,例如获取令牌、请求中的注入、自动续订……实际上只有几行配置,并且您将所有令牌管理抽象到身份模型框架中。

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

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