Web API Authorization via HttpWebRequest

Hoang Tran picture Hoang Tran · Nov 21, 2017 · Viewed 21.8k times · Source

I have a function to call my Web API. It works well if TestCallingRemotely is set to [AllowAnonymous].

var httpWebRequest = (HttpWebRequest)WebRequest.Create(
    "http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
    string input = "{}";

    streamWriter.Write(input);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

How do I pass the username and password to the HttpWebRequest for authorization?

I need to call my Web API from CLR integration, which only supports System.Net.

Answer

aaron picture aaron · Nov 21, 2017

ABP's startup template uses bearer token authentication infrastructure.

var token = GetToken(username, password);

// var httpWebRequest = (HttpWebRequest)WebRequest.Create(
//     "http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");
// httpWebRequest.ContentType = "application/json";
// httpWebRequest.Method = "POST";

httpWebRequest.Headers.Add("Authorization", "Bearer " + token);

// ...

Get token

This uses a crude way to extract the token, inspired by an MSDN article.

private string GetToken(string username, string password, string tenancyName = null)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(
        "http://localhost:6334/api/Account/Authenticate");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        var input = "{\"usernameOrEmailAddress\":\"" + username + "\"," +
                    "\"password\":\"" + password + "\"}";

        if (tenancyName != null)
        {
            input = input.TrimEnd('}') + "," +
                    "\"tenancyName\":\"" + tenancyName + "\"}";
        }

        streamWriter.Write(input);
        streamWriter.Flush();
        streamWriter.Close();
    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    string response;

    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        response = streamReader.ReadToEnd();
    }

    // Crude way
    var entries = response.TrimStart('{').TrimEnd('}').Replace("\"", String.Empty).Split(',');

    foreach (var entry in entries)
    {
        if (entry.Split(':')[0] == "result")
        {
            return entry.Split(':')[1];
        }
    }

    return null;
}