在服务器端用当前登入的用户身份请求某一页面
如果是Forms认证的话,实现起来很简单,因为相关的凭据都在cookie中,只要把所有的cookie都付给HttpWebRequest就可以了.
代码如下:
1 Uri uri = new Uri(url);
2 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
3 CookieContainer c = new CookieContainer();
4 for (int i = 0; i < curRequest.Cookies.Count; i++)
5 {
6 c.Add(new Cookie(curRequest.Cookies[i].Name, curRequest.Cookies[i].Value,
7 curRequest.Cookies[i].Path, uri.Host));
8 }
9 request.CookieContainer = c;
10 request.Method = "GET";
11 request.AllowAutoRedirect = false;
12 WebResponse response = request.GetResponse();
2 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
3 CookieContainer c = new CookieContainer();
4 for (int i = 0; i < curRequest.Cookies.Count; i++)
5 {
6 c.Add(new Cookie(curRequest.Cookies[i].Name, curRequest.Cookies[i].Value,
7 curRequest.Cookies[i].Path, uri.Host));
8 }
9 request.CookieContainer = c;
10 request.Method = "GET";
11 request.AllowAutoRedirect = false;
12 WebResponse response = request.GetResponse();
但是如果是Windows集成认证的话,身份凭据就不在cookie中的.因此需要调用LogonUserIdentity.Impersonate()来模拟,然后再取用户身份信息.
代码如下:
//HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//HttpRequest curRequest = Page.Request;
1 using (WindowsImpersonationContext context = curRequest.LogonUserIdentity.Impersonate())
2 {
3 NetworkCredential cred2 = (NetworkCredential)CredentialCache.DefaultCredentials;//再取就是登录的用户而不是当前iis运行账户
4 CredentialCache cache =new CredentialCache();
5 cache.Add(request.RequestUri, "NTLM", cred2);
6 request.Credentials = cache;
7 request.Method ="GET";
8 request.AllowAutoRedirect =false;
9 WebResponse response = request.GetResponse();
10 context.Undo();
11 }