Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 738
Green_qaue Avatar asked Feb 13 '17 13:02

Green_qaue


People also ask

What is token validation endpoint?

The token validation endpoint on the IBM MobileFirst™ Platform Server validates tokens that are issued by the authorization server. The token endpoint implements the OAuth 2.0 token introspection specification and validates access tokens and ID tokens.

What is the validity of bearer token?

A valid bearer token (with active access_token or refresh_token properties) keeps the user's authentication alive without requiring him or her to re-enter their credentials frequently. The access_token can be used for as long as it's active, which is up to one hour after login or renewal.

How do I send a bearer token in REST API?

To send a GET request with a Bearer Token authorization header, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.


2 Answers

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.

like image 191
Brandon Avatar answered Oct 20 '22 00:10

Brandon


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..
like image 1
Vitaliy Markitanov Avatar answered Oct 20 '22 00:10

Vitaliy Markitanov