patterncsharpMinor
Logging into WebAPI 2 site from c# desktop application
Viewed 0 times
loggingapplicationdesktopintowebapisitefrom
Problem
I'm trying to login into a webapi2 site from a desktop application. After a lot of googling, I cobbled together a working prototype. Since we are talking about security I wanted to do a peer review. I'm just starting with security design and I'm not exactly sure about my design.
The WebAPI site that is targeted is a wepapi 2 standard template out of visual studio.
I'm mainly looking for security issuesut general issues are also greatly appreciated.
One issue I'm aware of is that SSL should be added and with that ssl validation. I haven't implemented it yet.
```
static internal async Task GetWebAPIReguest(string siteUrl, string APIController, string userName, string Password)
{
TokenResponseModel Token = await GetBearerToken(siteUrl, userName, Password);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(siteUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token.AccessToken);
return await client.GetStringAsync(APIController);
}
static internal async Task GetBearerToken(string siteUrl, string Username, string Password)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(siteUrl);
client.DefaultRequestHeaders.Accept.Clear();
HttpContent requestContent = new StringContent("grant_type=password&username=" + Username + "&password=" + Password, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage responseMessage = await client.PostAsync("Token", requestContent);
if (responseMessage.IsSuccessStatusCode)
{
string jsonMessage;
using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())
{
jsonMessage = new StreamReader(responseStream).ReadToEnd();
}
TokenResponseModel tokenResponse = (TokenResponseModel)J
The WebAPI site that is targeted is a wepapi 2 standard template out of visual studio.
I'm mainly looking for security issuesut general issues are also greatly appreciated.
One issue I'm aware of is that SSL should be added and with that ssl validation. I haven't implemented it yet.
```
static internal async Task GetWebAPIReguest(string siteUrl, string APIController, string userName, string Password)
{
TokenResponseModel Token = await GetBearerToken(siteUrl, userName, Password);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(siteUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token.AccessToken);
return await client.GetStringAsync(APIController);
}
static internal async Task GetBearerToken(string siteUrl, string Username, string Password)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(siteUrl);
client.DefaultRequestHeaders.Accept.Clear();
HttpContent requestContent = new StringContent("grant_type=password&username=" + Username + "&password=" + Password, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage responseMessage = await client.PostAsync("Token", requestContent);
if (responseMessage.IsSuccessStatusCode)
{
string jsonMessage;
using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())
{
jsonMessage = new StreamReader(responseStream).ReadToEnd();
}
TokenResponseModel tokenResponse = (TokenResponseModel)J
Solution
I was going to make a very large post with altered code, but I don't fully understand what your code is doing so all I will suggest is that
Once again I'd give you a code sample but I just don't understand what your code is trying to do, which is my own fault, because I haven't really used much HTTP in .NET.
Here are the responsibilities of your two methods so far:
The majority of these should be in their own function.
- You need to use a consistent code style.
camelCasefor variables/arguments,PascalCasefor runtime constants (types/constants) and properties, and_camelCasefor private fields on an object.
- Your methods are simply doing way too much. Your 2 methods there are connecting to two different web pages, composing two URLs, parsing JSON into a POCO (and then back out again), and doing authentication on top of all of that.
- You aren't managing the lifecycle of
HttpClient. There is a general consensus that creating and disposingHttpClients is not the best use of a class. At the very least you should be Disposing of yourHttpClients but all you're doing in your current code is letting yourHttpClients leak. Consider that your functions do not need to know how to create aHttpClient, they just need to know how to connect to a Url - let the caller of the function do the heavy lifting for you.
Once again I'd give you a code sample but I just don't understand what your code is trying to do, which is my own fault, because I haven't really used much HTTP in .NET.
Here are the responsibilities of your two methods so far:
- Create a HttpClient
- Decode JSON into a POCO
- Create authentication token
- Compose url from base url, secondary url and a query string
- Apply authentication token to HttpClient
- Handle the response of one of the HttpClients
- Prepare HttpClient headers
The majority of these should be in their own function.
Context
StackExchange Code Review Q#44097, answer score: 6
Revisions (0)
No revisions yet.