获取当前请求的凭据以在WebRequest中使用

3

当用户访问我的网站时,他必须输入凭据。这些凭据基本上是普通的目录访问凭据。 在某个特定的点上,我通过调用来检查他们想要下载的某个文件是否存在

WebRequest req = HttpWebRequest.Create(checkUri.AbsoluteUri);
WebResponse res = req.GetResponse();

虽然我可以从浏览器访问checkUri,但在进行上述检查时却收到了401错误。我认为我需要设置

req.Credentials

但是我不知道当前凭据存储在哪里...

有什么想法吗?

--更新--

  • 综合Windows身份验证:否
  • 允许匿名:关闭
  • 呼叫者:同一网站页面上的链接(GET)
  • 模拟:默认关闭(甚至不知道如何在asp.net mvc中启用它)
3个回答

7

我在使用表单身份验证的网站上遇到了类似的问题,通过使用提供的代码(链接)中的第二个回复,我成功解决了这个问题。

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
// Add the current authentication cookie to the request
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
Cookie authenticationCookie = new Cookie(
    FormsAuthentication.FormsCookieName,
    cookie.Value,
    cookie.Path,
    HttpContext.Current.Request.Url.Authority);

req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(authenticationCookie);

WebResponse res = req.GetResponse();

5
我认为您需要的是这个:

我想您需要这个:

req.Credentials = CredentialCache.DefaultCredentials;

1
好的,我尝试了DefaultCredentials和DefaultNetworkCredentials。两个都不行。 - Boris Callens
你的网站是否开启了集成的Windows身份验证并关闭了匿名访问?是什么在发起调用?如果你的调用者本身就是一个网站,你是否开启了模拟和正确配置了Kerberos委派? - Dave Markle
谢谢评论。不确定关于模拟和Kerberos委派。我该如何检查? 将我所知道的放在OP中。 - Boris Callens

1

您需要启用集成的Windows身份验证。

我不知道在ASP.NET MVC中会发生什么,但在ASP.NET Web Forms中,模拟身份验证是通过以下方式打开的:

<identity impersonate="true"> 

in web.config.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接