401使用WebRequest对象调用Stormpath REST API时未授权?

时间:2015-11-04 08:06:03

标签: c# basic-authentication stormpath

我正在使用Stormpath进行身份验证服务。我使用HttpWebRequest调用Stormpath的RestAPI。

我也使用HttpWebRequest来调用RestAPI,但它不起作用。

private void BtnGetResetApiClick(object sender, EventArgs e)
{

var username = "aaaa";
var password = "bbbb";
ServicePointManager.ServerCertificateValidationCallback = Callback;
var request = WebRequest.Create("https://api.stormpath.com/v1/tenants/current") as HttpWebRequest;

request.UserAgent = ".NET SDK";
request.Method = "GET";
request.Accept = "*/*";

var data = string.Format("{0}:{1}", username, HttpUtility.HtmlEncode(password));

var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
string authHeader = string.Format("Basic {0}", token);

request.Headers.Add("Authorization", authHeader);
request.ServerCertificateValidationCallback = Callback;

using (var response = request.GetResponse())
{
    var stream = response.GetResponseStream();
    if (stream != null)
    {
        var streamReader = new StreamReader(stream);
        var str = streamReader.ReadToEnd();
        streamReader.Close();
        stream.Close();
    }
  }
}

private bool Callback(object obj, X509Certificate certificate, X509Chain  chain, SslPolicyErrors errors)
{
 return true;
}

致电:

var response = request.GetResponse()

我有一个例外:

  

System.dll中发生未处理的“System.Net.WebException”类型异常远程服务器返回错误:(401)未经授权。

你能帮我看看我的代码是否有问题吗?

1 个答案:

答案 0 :(得分:1)

更新 - 使用SDK,它更容易!

如果您经常从C#调用Stormpath API,请不要手动编写请求。请改用Stormpath .NET SDK。我是作者。 :)

使用程序包管理器控制台中的install-package Stormpath.SDK进行安装。然后,创建一个IClient对象:

// In a production environment, you'll want to load these from
// environment variables or a secure file, instead of hardcoding!
var apiKey = ClientApiKeys.Builder()
                 .SetId("Your_Stormpath_API_key_ID")
                 .SetSecret("Your_Stormpath_API_key_secret")
                 .Build();
var client = Clients.Builder()
                 .SetApiKey(apiKey)
                 .Build();

获取租户信息现在只是一个简单的电话:

var tenant = await client.GetCurrentTenantAsync();
Console.WriteLine($"Current tenant is: {tenant.Name}");

如果您真的想要提出原始请求,您仍然可以这样做!我将在下面解释。

构建授权标头

401 Unauthorized响应意味着API无法在您的请求中找到有效的授权标头。要正确验证,您需要两件事:

  • 格式apiKeyID:apiKeySecret
  • 的授权有效内容
  • Authorization标头,其值为Basic base64(payload)

以下是构建完整标题的方法:

// API_KEY_ID and API_KEY_SECRET populated elsewhere
var authPayload = string.Format("{0}:{1}", API_KEY_ID, API_KEY_SECRET);
var authPayloadEncoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(authPayload));
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + authPayloadEncoded);

您不需要ServerCertificateValidationCallback = Callback内容。使用上面的标题,API会将请求视为有效请求(假设您的API密钥ID和密钥是正确的)。

重定向处理

需要注意的一件事(首先让我绊倒!)是WebRequest将自动遵循HTTP 302重定向,但will not apply the existing headers会对新请求进行重定向。

解决方案是禁用以下重定向:

request.AllowAutoRedirect = false;

这意味着您必须自己处理302个响应,但这是将Authorization标头正确应用于每个请求的唯一方法。

工作示例

我在this gist中创建了一个简单的工作示例。由于我将多次创建请求,因此我编写了一个辅助函数:

private static HttpWebRequest BuildRequest(string method, string uri)
{
    var request = WebRequest.Create(uri) as HttpWebRequest;
    request.UserAgent = "dotnet/csharp web-request";
    request.Method = method;
    request.ContentType = "application/json";

    // Important, otherwise the WebRequest will try to auto-follow
    // 302 redirects without applying the authorization header to the
    // subsequent requests.
    request.AllowAutoRedirect = false;

    // Construct HTTP Basic authorization header
    var authPayload = string.Format("{0}:{1}", API_KEY_ID, API_KEY_SECRET);
    var authPayloadEncoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(authPayload));
    request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + authPayloadEncoded);

    return request;
}

一个简单的控制台应用程序,用于演示获取当前租户URL和名称:

// Get these from the Stormpath admin console
private static string API_KEY_ID = "Your_Stormpath_API_key_ID";
private static string API_KEY_SECRET = "Your_Stormpath_API_key_secret";

static void Main(string[] args)
{
    // First, we need to get the current tenant's actual URL
    string tenantUrl = null;
    var getCurrentTenantRequest = BuildRequest("GET", "https://api.stormpath.com/v1/tenants/current");

    try
    {
        using (var response = getCurrentTenantRequest.GetResponse())
        {
            tenantUrl = response.Headers["Location"];
        }
    }
    catch (WebException wex)
    {
        Console.WriteLine("Request failed. {0}", wex.Message);
        throw;
    }

    // Now that we have the real tenant URL, get the tenant info
    string tenantData = null;
    var getTenantInfoRequest = BuildRequest("GET", tenantUrl);

    try
    {
        using (var response = getTenantInfoRequest.GetResponse())
        using (var responseStream = response.GetResponseStream())
        using (var reader = new StreamReader(responseStream))
        {
            tenantData = reader.ReadToEnd();
        }
    }
    catch (WebException wex)
    {
        Console.WriteLine("Request failed. {0}", wex.Message);
        throw;
    }

    // Use JSON.NET to parse the data and get the tenant name
    var parsedData = JsonConvert.DeserializeObject<Dictionary<string, object>>(tenantData);
    Console.WriteLine("Current tenant is: {0}", parsedData["name"]);

    // Wait for user input
    Console.ReadKey(false);
}

代码非常冗长,因为我们正在向API发出原始请求。同样,如果您经常提出请求,请改用SDK!