Authentication

Access Token Security

The PartsSource ePartsFinder web services use Access Tokens to manage the user login session. An exchange will start by passing organization and user credentials to the web service and an Access Token will be returned. The Access Token must be maintained by the integrating solution and returned with every subsequent request. Since the token is utilized to identify the user, facility and permissions any request sent without a token will be rejected. Access Tokens will be active for a set period of time, as noted in the expires_in property. After that time or a period of inactivity they will expire. When an expired token is submitted the service will return a message stating that the token is expired and a new token will need to be created before the request can be sent back through. The integrating system should include methods for managing the creation, validation and recreation of Access Tokens during all interactions with PartsSource. These methods should be transparent to the end user.

Copy and paste the code below into a Visual Studio Console Application to see how Authentication works. Be sure to include a reference to the 3rd party library, Json.NET. It can be easily obtained through nuget, or try here: Jame Newton-King's Json.NET


using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;

namespace ApiTestConsole
{
    public class AuthInfo
    {
        public string access_token { get; set; }    // the actual token, a very long encrypted string
        public string token_type { get; set; }      // the type of token, currently bearer
        public int expires_in { get; set; }         // when the token expires in seconds
    }

    public class Program
    {
        static AuthInfo Login(string tokenUrl, string userName, string password, string subscription, string company)
        {
            // construct byte array to put into the request header
            byte[] content;
            
            if (!string.IsNullOrWhiteSpace(subscription) && !string.IsNullOrWhiteSpace(company))
                content = Encoding.UTF8.GetBytes(String.Format("grant_type=password&username={0}&password={1}&subscription={2}&company={3}", userName, password, subscription, company));
            else
                content = Encoding.UTF8.GetBytes(String.Format("grant_type=password&username={0}&password={1}", userName, password));

            // set up the web request
            var webRequest = WebRequest.Create(tokenUrl);
            webRequest.Credentials = CredentialCache.DefaultCredentials;
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = content.Count();
            // write the header contents to the stream
            webRequest.GetRequestStream().Write(content, 0, content.Count());
            // execute the request by calling the getResponse method
            using (var response = webRequest.GetResponse())
            {
                // read the response using a stream reader
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    // here's all the contents
                    var responseContent = reader.ReadToEnd();
                    // AuthInfo is defined above, and will contain the entire response
                    var auth = new AuthInfo();
                    // use nuget to use Newtonsoft.Json library to parse the Json.
                    JsonConvert.PopulateObject(responseContent, auth);
                    return auth;
                }
            }
        }
        static string TestRequest(string apiMethodUrl, AuthInfo authInfo)
        {
            // start creating a request.
            var request = (HttpWebRequest)WebRequest.Create(apiMethodUrl);
            request.Method = "GET";
            // write the oauth information to the header
            request.Headers.Add("Authorization", string.Format("{0} {1}", authInfo.token_type, authInfo.access_token));
            // get a response
            // do something witht the response
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                // Stream implements IDisposable - so using
                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream == null)
                        return default(string);
                    using (var reader = new StreamReader(responseStream))
                    {
                        var responseResults = reader.ReadToEnd();
                        return JsonConvert.DeserializeObject(responseResults);
                    }
                    // if we get here, nothing was returned from the request
                }
            }
        }
        static void Main(string[] args)
        {
            // login 
            var loginResults = Login("https://api.partsfinder.com/token", "replace-with-your-username", "replace-with-your-password", "replace-with-your-subscription", "replace-with-your-company");
            Console.WriteLine("token_type {0} access_token: {1} expires_in {2}", loginResults.token_type, loginResults.access_token, loginResults.expires_in);
            // using the login, request a service resource
            var partsFinderUrl = TestRequest("https://api.partsfinder.com/api/uri/partsfinder", loginResults);
            Console.WriteLine("Parts Finder Url: {0}", partsFinderUrl);
        }
    }
}