What is OAuth2?
OAuth 2.0 is the industry-standard protocol for authorization. OAuth 2.0 supersedes the work done on the original OAuth protocol created in 2006. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices.
reference: https://oauth.net/2/
Who uses OAuth2?
Among them you may have heard of Facebook, GitHub
Login and get your Token!
Create an object to hold your credentials, to send your data across the internet securely, you will need to encode your credentials, so you will do that on the Values method
[DataContract] public class AuthorizationRequest { [DataMember] public string email { get; set; } [DataMember] public string password { get; set; } [DataMember] public string client_id { get; set; } [DataMember] public string client_secret { get; set; } public List<KeyValuePair<string, string>> Values { get { var values = new List<KeyValuePair<string, string>>(); values.Add(new KeyValuePair<string, string>("email", email)); values.Add(new KeyValuePair<string, string>("password", password)); values.Add(new KeyValuePair<string, string>("client_id", client_id)); values.Add(new KeyValuePair<string, string>("client_secret", client_secret)); return values; } } }
Once you have your credentials holder you can implement a Login method.
You will need to get a client_id and client_secret from your provider.
async Task<AuthorizationResponse> Login() { AuthorizationRequest letMeIn = new AuthorizationRequest(); letMeIn.email = "send@email.com"; letMeIn.password = "mypassword"; letMeIn.client_id = "XXXXXX"; letMeIn.client_secret = "XXXXXX"; var values = letMeIn.Values; try { string url = "www.yourURL.com/"; using (var httpClient = new HttpClient()) { using (var content = new FormUrlEncodedContent(values)) { content.Headers.Clear(); content.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); HttpResponseMessage response = await httpClient.PostAsync(url, content); var contents = await response.Content.ReadAsStringAsync(); var model = JsonConvert.DeserializeObject<AuthorizationResponse>(contents); return model; } } } catch (Exception ex) { Response.Write(ex.Message); return null; } }
If you want to test this, create new ASP.Net application, and on the index.aspx implement this code:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web.UI; using Intralinks.Models; using Newtonsoft.Json; public partial class Index : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { RegisterAsyncTask(new PageAsyncTask(BindData)); } private async System.Threading.Tasks.Task BindData() { try { var credentials = await Login(); Response.Write(credentials.access_token); } catch (Exception ex) { Response.Write(ex.Message); } } }
One thought on “OAuth2 – Get an Access Token – C#”