简体   繁体   中英

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.
  • 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 . You can do it in C# like so:

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.

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.

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/

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:

  1. Server Side : 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/ . 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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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