-
-
Save TehWardy/b0200317845b75940b1ef27d45414c3c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using log4net; | |
using Newtonsoft.Json.Linq; | |
using System; | |
using System.Collections.Specialized; | |
using System.Configuration; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Web; | |
using System.Web.SessionState; | |
namespace Core.Objects | |
{ | |
public static class HttpClientExtensions | |
{ | |
static readonly ILog log = LogManager.GetLogger(typeof(HttpClient)); | |
/// <summary> | |
/// Adds authorization information to the client by making an auth call with the given credentials | |
/// </summary> | |
/// <param name="client">The HttpClient to attach the authorization information to</param> | |
/// <param name="user">The username to use for authentication</param> | |
/// <param name="pass">The password to use for authentication</param> | |
/// <returns>An authenticated HttpClient</returns> | |
public static async Task<JObject> Authenticate(this HttpClient client, string user, string pass) | |
{ | |
var authRequest = await client.PostAsync("Authenticate", new StringContent("username=" + user + "&password=" + pass + "&grant_type=password")); | |
var authResponse = await authRequest.Content.ReadAsStringAsync(); | |
if (!authResponse.StartsWith("<!DOCTYPE")) | |
{ | |
dynamic token = JObject.Parse(authResponse); | |
try { | |
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type.ToString(), token.access_token.ToString()); | |
return token; | |
} | |
catch { /* if we get here the server returned a json repsonse but it wasn't a token, it was more than likely an auth failure. */ } | |
} | |
else log.Warn("Auth request Failed for user " + user); | |
return null; | |
} | |
/// <summary> | |
/// Adds the given collection of header values to an instance of a http client | |
/// </summary> | |
/// <param name="client">the http client</param> | |
/// <param name="headers">the header values to add</param> | |
/// <returns>HttpClient with the given header values</returns> | |
public static HttpClient AddHeaders(this HttpClient client, NameValueCollection headers) | |
{ | |
foreach (var key in headers.Keys) | |
try { client.DefaultRequestHeaders.Add(key.ToString(), headers.Get(key.ToString())); } catch { } | |
return client; | |
} | |
public static HttpClient UseBasicAuth(this HttpClient client, string user, string pass) | |
{ | |
var base64AuthString = Convert.ToBase64String(Encoding.UTF8.GetBytes("username=" + user + "&password=" + pass + "&grant_type=password")); | |
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("basic", base64AuthString); | |
return client; | |
} | |
public static HttpClient UseBaseUrl(this HttpClient client, string url) | |
{ | |
client.BaseAddress = new Uri(url); | |
return client; | |
} | |
/// <summary> | |
/// Adds authorization information from the given session to the given HttpClient | |
/// </summary> | |
/// <param name="client">The HttpClient to attach the authorization information to</param> | |
/// <param name="request">The HttpSessionState from which to acquire the authorization information</param> | |
/// <returns>An authenticated HttpClient</returns> | |
public static HttpClient AddAuthFromSession(this HttpClient client, HttpSessionStateBase session) | |
{ | |
if (client.DefaultRequestHeaders.Authorization == null) | |
client.DefaultRequestHeaders.Add("Authorization", "bearer " + ((JObject)session["token"])["access_token"].ToString()); | |
return client; | |
} | |
/// <summary> | |
/// Adds authorization information from the given session to the given HttpClient | |
/// </summary> | |
/// <param name="client">The HttpClient to attach the authorization information to</param> | |
/// <param name="request">The HttpSessionState from which to acquire the authorization information</param> | |
/// <returns>An authenticated HttpClient</returns> | |
public static HttpClient AddAuthFromSession(this HttpClient client, HttpSessionState session) | |
{ | |
if(client.DefaultRequestHeaders.Authorization == null && session != null) | |
client.DefaultRequestHeaders.Add("Authorization", "bearer " + ((JObject)session["token"])["access_token"].ToString()); | |
return client; | |
} | |
/// <summary> | |
/// Adds authorization information from the given request to the given HttpClient | |
/// </summary> | |
/// <param name="client">The HttpClient to attach the authorization information to</param> | |
/// <param name="request">The HttpRequest from which to acquire the authorization information</param> | |
/// <returns>An authenticated HttpClient</returns> | |
public static HttpClient AddAuthFromRequest(this HttpClient client, HttpRequest request) | |
{ | |
var auth = request.Headers["authorization"]; | |
if(auth != null && client.DefaultRequestHeaders.Authorization == null) client.DefaultRequestHeaders.Add("Authorization", auth); | |
return client; | |
} | |
/// <summary> | |
/// Sets the base URI on the given HttpClient instance to the one in config | |
/// </summary> | |
/// <param name="client">the HttpClient</param> | |
/// <returns>The HttpClient (updated)</returns> | |
public static HttpClient WithApiBaseUriFromConfig(this HttpClient client) | |
{ | |
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["ApiUrl"]); | |
return client; | |
} | |
public static HttpClient AddAuthToken(this HttpClient client, string token) | |
{ | |
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token); | |
return client; | |
} | |
/// <summary> | |
/// Does a HttpGET and parses the repsonse in to the response type T | |
/// </summary> | |
/// <typeparam name="T">Type of the result</typeparam> | |
/// <param name="client">the HttpClient to use</param> | |
/// <param name="url">the relative url to the endpoint to call</param> | |
/// <returns>The API's response result of type T</returns> | |
public static Task<T> GetAsync<T>(this HttpClient client, string url) | |
{ | |
return client.GetAsync(url) | |
.ContinueWith(t => t.Result.Content.ReadAsAsync<T>()) | |
.Unwrap(); | |
} | |
/// <summary> | |
/// Determines the API base url (from config), token information (from session) and does a HttpGET | |
/// and parses the repsonse in to the response type T | |
/// </summary> | |
/// <typeparam name="T">Type of the result</typeparam> | |
/// <param name="client">the HttpClient to use</param> | |
/// <param name="url">the relative url to the endpoint to call</param> | |
/// <returns>The API's response result of type T</returns> | |
public static Task<T> SecureGetAsync<T>(this HttpClient client, string url) | |
{ | |
return client | |
.WithApiBaseUriFromConfig() | |
.AddAuthFromSession(HttpContext.Current?.Session) | |
.GetAsync<T>(url); | |
} | |
/// <summary> | |
/// Determines the API base url (from config), token information (from session) and does an api post | |
/// </summary> | |
/// <typeparam name="T">Type of data being posted</typeparam> | |
/// <param name="client">The HttpClient to use</param> | |
/// <param name="url">the relative API url to post to</param> | |
/// <param name="value">the business object to post of type T</param> | |
/// <returns>The Http response form the API</returns> | |
public async static Task<HttpResponseMessage> SecurePostAsync<T>(this HttpClient client, string url, T value) | |
{ | |
return await client | |
.WithApiBaseUriFromConfig() | |
.AddAuthFromSession(HttpContext.Current?.Session) | |
.PostAsJsonAsync(url, value); | |
} | |
/// <summary> | |
/// Determines the API base url (from config), token information (from session) and does an api post | |
/// and then parses the result | |
/// </summary> | |
/// <typeparam name="T">Type of data being posted</typeparam> | |
/// <typeparam name="TResult">typeo fthe result</typeparam> | |
/// <param name="client">The HttpClient to use</param> | |
/// <param name="url">the relative API url to post to</param> | |
/// <param name="value">the business object to post of type T</param> | |
/// <returns>An object of type TResult</returns> | |
public async static Task<TResult> SecurePostAsync<T, TResult>(this HttpClient client, string url, T value) | |
{ | |
return await client.SecurePostAsync<T>(url, value) | |
.ContinueWith(t => t.Result.Content.ReadAsAsync<TResult>()) | |
.Unwrap(); | |
} | |
public async static Task<HttpClient> ConfigureFromConfig(this HttpClient client) | |
{ | |
if (ConfigurationManager.AppSettings["apiUrl"] != null) | |
client = client.WithApiBaseUriFromConfig(); | |
if (ConfigurationManager.AppSettings["AppUser"] != null && ConfigurationManager.AppSettings["AppPass"] != null) | |
await client.Authenticate(ConfigurationManager.AppSettings["AppUser"].ToString(), ConfigurationManager.AppSettings["AppPass"].ToString()); | |
return client; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment