【发布时间】:2015-07-08 00:22:51
【问题描述】:
好的,所以我正在编写一个程序来访问 RESTful 服务,但我首先必须为网站提供身份验证。我有有效的凭据,我的整个代码如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Net;
using System.IO;
namespace AccessAPI
{
class Program
{
static void Main(string[] args)
{
string uri = "http://domainName/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
string auth = CreateAuthorization("http://domainName/", "my\\username", "password");
request.Headers["Authorization"] = "Basic " + auth;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
}
static string CreateAuthorization(string realm, string userName, string password)
{
string auth = ((realm != null) && (realm.Length > 0) ?
realm + @"\" : "") + userName + ":" + password;
auth = Convert.ToBase64String(Encoding.Default.GetBytes(auth));
return auth;
}
}
}
我使用其他论坛上发布的一些解决方案已经走到了这一步。虽然这似乎对某些人有用,但对我来说却不行。首先,我知道凭据是准确的。我可以通过网络浏览器输入它们,并且它们的行为与应有的一样。另外,我确保其中的任何“\”(用户名中有一个)在代码中用“\\”表示。但是,每次运行此程序时,我都会不断返回“远程服务器返回错误:(401)未经授权。” 谁能帮我解决这个问题?感谢您的宝贵时间!
【问题讨论】:
-
REST 服务是否使用基本身份验证?一个非常常见的做法是拥有一个名为“login”或“auth”或其他任何名称的资源,将凭据传递给它,获取授权令牌然后使用该令牌,您需要阅读服务文档。查看哪种授权机制使用。
标签: c# authentication web passwords httpwebrequest