我有一个函数可以调用我的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();
如何将username
和password
传递给HttpWebRequest
授权?
我需要从CLR Integration调用我的Web API,它仅支持System.Net
。
abp的启动模板使用携带者令牌身份验证基础结构。
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);
// ...
获取令牌
这使用一种粗略的方法来提取令牌,灵感来自MSDN文章。
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;
}
如果服务器使用基本身份验证,则可以添加这样的标题:
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();