For non-web applications that cannot use the HTTP redirection flows, a user identifying Access Token
can be obtained from the Authorization Server using the Resource Owner
OAuth Flow.
This uses the Client ID
and Client Secret
that the application developer registered
on CodeProject to validate the client, and the user's CodeProject.com email and password to validate the user.
Note:
The demos use a pre-registered Client ID
and Client Secret
. For your
apps, you will need to register your own.
Information about registering a Client ID
and Client Secret
can be found here.
The following code demonstrates a C# console application that gets an Access Token using Resource Owner credentials, and then queries the server for the
Note: that the request is made using HTTPS
. HTTP
requests
will fail.
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; namespace ConsoleApplication3 { class ProgramRO { /// The client information used to get the OAuth Access Token from the server. static string clientId = "JkOnJ9zIQ1vWvP3FvsJVx-3iOnSd-6a-"; static string clientSecret = "U_ZHCQackGJHW4-Jn4qfGce6JLV9qAKhJEGahyRHVpeYVWf_r8iSaSt4z6AZn8kC"; // The server base address static string baseUrl = "https://api.codeproject.com/"; // this will hold the Access Token returned from the server. static string accessToken = null; static void Main(string[] args) { Console.WriteLine("Starting ..."); DoIt().Wait(); Console.ReadLine(); } /// <summary> /// This method does all the work to get an Access Token and read the first page of /// Articles from the server. /// </summary> /// <returns></returns> private static async Task<int> DoIt() { // Get the Access Token. accessToken = await GetAccessToken(); Console.WriteLine( accessToken != null ? "Got Token" : "No Token found"); if (accessToken != null) { var profile = await MyProfile(); var reputation = await MyReputation(); Console.WriteLine("Hello {0},", profile.userName); Console.WriteLine("Your CodeProject MemberId is {0} and your Reputation Points are {1}.", profile.codeProjectMemberId, reputation.totalPoints); // Get the Articles Console.WriteLine(); Console.WriteLine("------ My Articles ------"); dynamic response = await MyArticles(1); if (response.items != null) { var articles = (dynamic)response.items; foreach (dynamic article in articles) { Console.WriteLine("Title: {0}", article.title); } } // Get the Articles Console.WriteLine(); Console.WriteLine("------ My Questions ------"); response = await MyQuestions(1); if (response.items != null) { var questions = (dynamic)response.items; foreach (dynamic question in questions) { Console.WriteLine("Title: {0}", question.title); } } } return 0; } /// <summary> /// This method uses the OAuth Client Credentials Flow to get an Access Token to provide /// Authorization to the APIs. /// </summary> /// <returns></returns> private static async Task<string> GetAccessToken() { if (accessToken == null) using (var client = new HttpClient()) { Console.Write("Enter Email Address: "); var email = Console.ReadLine(); Console.Write("Enter Password: "); var fgColour = Console.ForegroundColor; Console.ForegroundColor = Console.BackgroundColor; var password = Console.ReadLine(); Console.ForegroundColor = fgColour; client.BaseAddress = new Uri(baseUrl); // We want the response to be JSON. client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Build up the data to POST. List<keyvaluepair<string, string>> postData = new List<KeyValuePair<string, string>>(); 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)); postData.Add(new KeyValuePair<string, string>("username", email)); postData.Add(new KeyValuePair<string, string>("password", password)); FormUrlEncodedContent content = new FormUrlEncodedContent(postData); // Post to the Server and parse the response. HttpResponseMessage response = await client.PostAsync("Token", content); string jsonString = await response.Content.ReadAsStringAsync(); object responseData = JsonConvert.DeserializeObject(jsonString); // return the Access Token. accessToken = ((dynamic)responseData).access_token; } return accessToken; } /// <summary> /// Gets the user's Profile. /// </summary> /// <returns>The user's Profile.</returns> private static async Task<dynamic> MyProfile() { using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Add the Authorization header with the AccessToken. client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); // create the URL string. string url = string.Format("v1/My/Profile"); // make the request HttpResponseMessage response = await client.GetAsync(url); // parse the response and return the data. string jsonString = await response.Content.ReadAsStringAsync(); object responseData = JsonConvert.DeserializeObject(jsonString); return (dynamic)responseData; } } /// <summary> /// Gets the user's Reputation. /// </summary> /// <returns>The user's Reputation.</returns> private static async Task<dynamic> MyReputation() { using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Add the Authorization header with the AccessToken. client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); // create the URL string. string url = string.Format("v1/My/Reputation"); // make the request HttpResponseMessage response = await client.GetAsync(url); // parse the response and return the data. string jsonString = await response.Content.ReadAsStringAsync(); object responseData = JsonConvert.DeserializeObject(jsonString); return (dynamic)responseData; } } /// <summary> /// Gets the page of Articles. /// </summary> /// <param name="page">The page to get.</param> /// <returns>The page of articles.</returns> private static async Task<dynamic> MyArticles(int page) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Add the Authorization header with the AccessToken. client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); // create the URL string. string url = string.Format("v1/My/Articles?page={0}", page); // make the request HttpResponseMessage response = await client.GetAsync(url); // parse the response and return the data. string jsonString = await response.Content.ReadAsStringAsync(); object responseData = JsonConvert.DeserializeObject(jsonString); return (dynamic)responseData; } } /// <summary> /// Gets the page of Questions. /// </summary> /// <param name="page">The page to get.</param> /// <returns>The page of articles.</returns> private static async Task<dynamic> MyQuestions(int page) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Add the Authorization header with the AccessToken. client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); // create the URL string. string url = string.Format("v1/My/Questions?page={0}", page); // make the request HttpResponseMessage response = await client.GetAsync(url); // parse the response and return the data. string jsonString = await response.Content.ReadAsStringAsync(); object responseData = JsonConvert.DeserializeObject(jsonString); return (dynamic)responseData; } } } }
This produces the output similar to:
Starting ... Enter Email Address: xxxxxw@cyyyyyyyt.com Enter Password: Got Token Hello Bob the Alien, Your CodeProject MemberId is 123456 and your Reputation Points are 42. ------ My Articles ------ Title: BaconLispum Title: Multi zip Test Title: Video test Title: Using Munq IOC Container Version 3 in ASP.NET MVC 3 Title: Aimee.NET - Faster Unit Tests and Refactoring the Documents Folder Title: Aimee.NET - Refactoring Lucene.NET: Setting up the Project ------ My Questions ------ Title: How do I make the Question List work with Search. Title: Anoher question for me Title: This is a question about something Title: How do I store and retrieve in real time from Lucene? Title: What is the question to the answer for everything which is 42? Title: Asp.Net Routing testing question