首页 文章

HttpWebRequest和身份验证

提问于
浏览
0

我正在尝试使用带有httpwebrequest的Forms Authenication,但我似乎没有任何成功 . 这是我在做的事情:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

request.Method = WebRequestMethods.Http.Get;

// Authentication items -------------------------------------------
request.UseDefaultCredentials = false;
request.PreAuthenticate = true;

// Attempt to set username and password:
CredentialCache cc = new CredentialCache();
cc.Add(
new Uri(url),
"Basic",
new NetworkCredential("username", "validpassword", "domain")
);
request.Credentials = cc;

request.AllowAutoRedirect = true;
request.KeepAlive = true;
request.Timeout = 10000;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;

// request html
response = (HttpWebResponse)request.GetResponse();

问题是,即使使用域的有效密码和用户名,这也总是引发异常 .

有人可以帮忙吗?

笔记:

  • 异常类型:WebException

  • 异常消息:"The remote server returned an error: (401) Unauthorized."

  • 异常状态:协议

  • 错误异常发生在:response =(HttpWebResponse)request.GetResponse();

  • 异常堆栈跟踪:无...抱歉

1 回答

  • 1

    我为HttpWebRequest添加了Credentials .

    myReq.UseDefaultCredentials = true;
      myReq.PreAuthenticate = true;
      myReq.Credentials = CredentialCache.DefaultCredentials;
    

    我想知道你遇到的401错误的子状态代码 . 401错误包含以下子状态代码:

    401.1:  Access is denied due to invalid credentials.
    401.2:  Access is denied due to server configuration favoring an alternate authentication method. 
    401.3:  Access is denied due to an ACL set on the requested resource.
    401.4:  Authorization failed by a filter installed on the Web server.
    401.5:  Authorization failed by an ISAPI/CGI application.
    401.7:  Access denied by URL authorization policy on the Web server.
    

    因为该项目在您的计算机上运行良好,我怀疑它是一个进程标识问题 . 默认情况下,IIS 6.0中的应用程序池使用“网络服务”作为其标识 . 此帐户受到限制,因此您可能会遇到访问拒绝问题 .

    出于故障排除目的,请尝试将应用程序池的标识更改为“本地系统” . 如果此方法可以解决此问题,请将标识更改回“网络服务”,并为要读取/写入的xml文件授予读/写权限 .

    关于如何更改应用程序池的标识,请参考以下步骤:

    1. Open IIS manager (Start | Control Panel | Administrative Tools | Internet Information Services Manager).
    2. Expand the “Application Pools” node.
    3. Right click the application pool which your project is using, and then select “Properties”.
    4. Click “Identity” tab.
    5. Choose “Local System” in the Predefined dropdown list.
    

    关于如何授予文件权限,请检查以下步骤:

    1. Open Windows Explorer.
    2. Right click the file, and then select "Properties".
    3. Click the "Security" tab.
    4. Add "Network Service" in access list and check "Modify", "Read", and "Write" for it.
    

    此外,其他文件也可能导致此问题,您可以使用Filemon监视任何访问文件拒绝问题 .

    FileMon for Windows v7.04 http://www.microsoft.com/technet/sysinternals/FileAndDisk/Filemon.mspx

相关问题