Sending a bearer token to endpoint, then validate this token
Asked Answered
N

2

7

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.

Nunhood answered 13/2, 2017 at 13:16 Comment(0)
B
14

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/

If this isn't sufficient then you should post more specific information about your use case and what you know.

Bromide answered 13/2, 2017 at 13:56 Comment(0)
H
2

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..
Hoiden answered 21/1, 2020 at 22:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.