我正在尝试在内部ASP.Net MVC C#工具中创建一种自动登录功能,该功能将使支持用户能够快速登录到他们支持的各种系统。
我已经能够通过Ajax / jQuery将完成登录表单所需的所有值传递给控制器,然后传递给类。如下所示,我可以基于if来打开各种URL,但不能完成登录表单。
我一直在研究httpwebrequests,但不确定如何构造一个结构以使用变量值(如下所示)来完成各种登录表单字段,然后单击按钮。
public AutoLogin(string Environment, string Username, string OrgId, string UserId, string OrgKey)
{
var env = Environment;
var user = Username;
var org = OrgId;
var userid = UserId;
var orgKey = OrgKey;
if (env == "system1")
{
string url = website;
CookieContainer cookieJar = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)";
req.Method = "POST";
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
req.KeepAlive = true;
req.Headers.Add("Keep-Alive: 300");
req.AllowAutoRedirect = false;
req.ContentType = "application/x-www-form-urlencoded";
req.CookieContainer = cookieJar;
string username = user;
string pw = "password";
string orgUid = orgKey;
StreamWriter sw = new StreamWriter(req.GetRequestStream());
sw.Write("userEmail=" + username + "&userPass=" + pw + "&orgUid=" + orgUid);
sw.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
//Add cookies to CookieJar (Cookie Container)
foreach (Cookie cookie in response.Cookies)
{
cookieJar.Add(new Cookie(cookie.Name.Trim(), cookie.Value.Trim(), cookie.Path, cookie.Domain));
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(1255));
string tmp = reader.ReadToEnd();
response.Close();
}
else if (env == "system2")
{
System.Diagnostics.Process.Start(url2);
}
else if (env == "system3")
{
System.Diagnostics.Process.Start(url3);
}
else
{
}
}
更新:
添加了我一直在使用的httpwebrequet代码,但是单击按钮前端时,它无法导航/打开网页。
答案 0 :(得分:0)
对于内部网站,最简单的方法是在网站中使用Windows身份验证。只需使用密码解锁您的PC,然后无需登录即可访问内部网站。 Windows可以“在后台”进行身份验证。 Web.config:
<authentication mode="Windows" />