web-dev-qa-db-ja.com

HttpWebRequestによるWeb API承認

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

承認のためにusernamepasswordHttpWebRequestに渡すにはどうすればよいですか?

System.NetのみをサポートするCLR統合からWeb APIを呼び出す必要があります。

4
Hoang Tran

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;
}
9
aaron

サーバーが基本認証を使用する場合は、次のようにヘッダーを追加できます。

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