2015-04-28 390 views
0

好的,所以我正在编写一个程序来访问一个RESTful服务,但我首先必须为网站提供身份验证。我有有效的凭据,我的整个代码如下所示:HttpWebRequest身份验证不起作用

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)未经授权。” 任何人都可以帮我解决这个问题吗?感谢您的时间!

+0

REST服务使用基本身份验证吗?一个非常普遍的做法是拥有名为“login”或“auth”或其他任何资源的资源,将凭据传递给它,获取授权令牌,然后使用该令牌,您需要阅读服务文档以查看哪种授权机制使用。 – Gusman

回答

0

非常感谢Gusman和Prashant,您的意见帮助我引导了正确的方向并最终取得了成功。所以Gusman,你是对的,这不仅仅是任何认证标准,它是使用Window的IIS服务。谷歌搜索如何做,与HttpWebRequest的促使我建立这个:

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://domain.name/"; 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 
      request.Method = "GET"; 
      request.UseDefaultCredentials = false; 
      request.PreAuthenticate = true; 
      request.Credentials = new NetworkCredential("username", "password"); 
      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
      StreamReader reader = new StreamReader(response.GetResponseStream()); 
      Console.WriteLine(reader.ReadToEnd()); 
     } 
    } 
} 

现在为什么这个工程,而其他的尝试都没有,我不知道。但是,这一切的症结似乎仅基于行

request.Credentials = new NetworkCredential("username", "password"); 

其中,顺便说一句,PRASHANT,工作时我不使用全http://domain.name/,就像你说的。 那么,希望如果其他人有这个完全相同的问题,他们将能够找到这个线程,并弄清楚事情。

0

从上面的代码,当“身份验证”字符串得到由身份验证字符串像这样的:“http://domainName/:my \用户名:密码”

中的验证字符串应该真正的格式为:域名\用户名:密码(域名是可选的)。