Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API Authorization via HttpWebRequest

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.

like image 477
Hoang Tran Avatar asked Nov 21 '17 09:11

Hoang Tran


People also ask

How do I authorize Web API?

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action. You can apply the filter globally, at the controller level, or at the level of individual actions.

What is the difference between HttpWebRequest and WebRequest?

In a nutshell, WebRequest—in its HTTP-specific implementation, HttpWebRequest—represents the original way to consume HTTP requests in . NET Framework. WebClient provides a simple but limited wrapper around HttpWebRequest. And HttpClient is the new and improved way of doing HTTP requests and posts, having arrived with .

How do I pass HttpWebRequest username and password?

UseDefaultCredentials = true; req. Credentials = new NetworkCredential("[email protected]", "somepassword"); HttpWebResponse response = (HttpWebResponse)req. GetResponse(); response. Close();

What is HttpWebRequest?

The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.


2 Answers

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;
}
like image 88
aaron Avatar answered Oct 18 '22 20:10

aaron


If the server uses basic authentication you can add the header like this:

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

var username = "Aladdin";
var password = "opensesame";

var bytes = Encoding.UTF8.GetBytes($"{username}:{password}");
httpWebRequest.Headers.Add("Authorization", $"Basic {Convert.ToBase64String(bytes)}");

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

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

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
like image 20
peco Avatar answered Oct 18 '22 18:10

peco