通过HttpWebRequest进行Web API授权

时间:2017-11-21 09:34:07

标签: c# asp.net-web-api httpwebrequest aspnetboilerplate http-request-parameters

我有一个调用我的Web API的函数。如果TestCallingRemotely设置为[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();

如何将usernamepassword传递给HttpWebRequest进行授权?

我需要从CLR集成调用我的Web API,它只支持System.Net

2 个答案:

答案 0 :(得分:6)

ABP的启动模板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);

// ...

获取令牌

这是一种粗略的方式来提取令牌,灵感来自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;
}

答案 1 :(得分:4)

如果服务器使用基本身份验证,您可以添加如下标题:

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();