@manhng

Welcome to my blog!

Test Api

October 5, 2017 11:40

Test API using IdentityServer4 for Auth & ASP.NET Core Web API

 

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ConsoleApp
{
internal class Program
{
private static void Main(string[] args)
{
var enterResult = "";
while (enterResult != "Exit")
{
Console.WriteLine("Choose an action: ");
Console.WriteLine("1. LogIn");
Console.WriteLine("2. Exit");
switch (Console.ReadLine())
{
case "1":
DoSomething();
break;

case "2":
enterResult = "Exit";
break;

default:
break;
}
}
}

private static void DoSomething()
{
const string userName = "auditor@gmail.com";
const string password = "Abc@123";
const string apiBaseAuthUri = "http://192.168.2.26:5000";
const string apiBaseUri = "http://192.168.2.26:8889/Service";
const string apiProjectsGetdata = "/api/Projects/GetData";

//Get the token
var token = GetApiToken(userName, password, apiBaseAuthUri).Result;
Console.WriteLine("Token: {0}", token);

//Make the call
var response = GetRequest(token, apiBaseUri, apiProjectsGetdata).Result;
Console.WriteLine("response: {0}", response);
}

private static async Task<string> GetApiToken(string userName, string password, string apiBaseUri)
{
using (var client = new HttpClient())
{
//setup client
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

//setup login data
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("client_id", "ro.client"),
new KeyValuePair<string, string>("client_secret", "secret"),
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", userName),
new KeyValuePair<string, string>("password", password),
});

//send request
HttpResponseMessage responseMessage = await client.PostAsync("/connect/token", formContent);

//get access token from response body
var responseJson = await responseMessage.Content.ReadAsStringAsync();
var jObject = JObject.Parse(responseJson);
return jObject.GetValue("access_token").ToString();
}
}

public static async Task<string> GetRequest(string token, string apiBaseUri, string requestPath)
{
using (var client = new HttpClient())
{
//setup client
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

//make request
HttpResponseMessage response = await client.GetAsync(requestPath);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}
}
}

Categories

Recent posts