Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

oAuth 2.0 API Consumption via C#

Our client had a requirement to integrate their API with the website that we are developing for them. And the API authentication is done via oAuth 2.0. They have provided all the necessary info as to (Client ID, Client Secret, Token Uri etc).

However we have hard time understanding the code snippet to call this via C#. We know we have to request a request token and attach that to header for the subsequent requests. We tried DotNetOpenAuth and Owin, but unable to find the actual code to implement this/did not succeed so far. Can any one help me with a small piece of C# code to achieve this?

like image 979
My Helper Avatar asked Jun 21 '16 01:06

My Helper


1 Answers

To request the access token you only need to do a request posting the authentication data. This code has been extracted from a working MVC app using the resource owner password credentials grant:

using (var client = new HttpClient())
{
    var postData = new List<KeyValuePair<string, string>>();
    postData.Add(new KeyValuePair<string, string>("username", _user));
    postData.Add(new KeyValuePair<string, string>("password", _pwd));
    postData.Add(new KeyValuePair<string, string>("grant_type", "password"));
    postData.Add(new KeyValuePair<string, string>("client_id", _clientId));
    postData.Add(new KeyValuePair<string, string>("client_secret", _clientSecret));

    HttpContent content = new FormUrlEncodedContent(postData);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

    var responseResult = client.PostAsync(_tokenUrl, content).Result;

    return responseResult.Content.ReadAsStringAsync().Result;
}

I hope it helps.

EDIT

Here you have a code snippet refreshing the token:

using (var client = new HttpClient())
{
    var postData = new List<KeyValuePair<string, string>>();
    postData.Add(new KeyValuePair<string, string>("refresh_token", _refreshToken));
    postData.Add(new KeyValuePair<string, string>("grant_type", "refresh_token"));
    postData.Add(new KeyValuePair<string, string>("client_id", _clientId));
    postData.Add(new KeyValuePair<string, string>("client_secret", _clientSecret));

    HttpContent content = new FormUrlEncodedContent(postData);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

    var responseResult = client.PostAsync(_tokenUrl, content).Result;

    return responseResult.Content.ReadAsStringAsync().Result;
}

And using it:

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
    HttpResponseMessage result = client.GetAsync(_url).Result;

    if (result.StatusCode == HttpStatusCode.Unauthorized)
    {
        RefreshToken(); /* Or reenter resource owner credentials if refresh token is not implemented */
        if (/* token refreshed, repeat the request using the new access token */)
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _newAccessToken);

            result = client.GetAsync(_url).Result;

            if (result.StatusCode == HttpStatusCode.Unauthorized)
            {
                // Process the error
            }
        }
    }

    return result;
}
like image 75
jumuro Avatar answered Oct 16 '22 19:10

jumuro