Web API Authorization via HttpWebRequest
Asked Answered
K

2

7

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.

Khanna answered 21/11, 2017 at 9:34 Comment(0)
H
13

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;
}
Haplology answered 21/11, 2017 at 16:0 Comment(0)
S
5

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();
Secularism answered 21/11, 2017 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.