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<string> 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<TokenResponseModel> 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)JsonConvert.DeserializeObject(jsonMessage, typeof(TokenResponseModel));
return tokenResponse;
}
else
{
return null;
}
}
class TokenResponseModel
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("userName")]
public string Username { get; set; }
[JsonProperty(".issued")]
public string IssuedAt { get; set; }
[JsonProperty(".expires")]
public string ExpiresAt { get; set; }
}