【发布时间】:2011-10-11 08:31:40
【问题描述】:
我们正在构建一个命令行应用程序,它需要使用表单身份验证从 IIS 服务器获取一些数据。如何从命令行应用程序进行表单身份验证?我试过了,但发生的只是请求被重定向到登录页面。
我猜如果我可以在请求中包含一个身份验证 cookie 以及正确的凭据,下载就可以了。
我可以控制客户端和服务器。我可以在 web.config 中设置 machineKey,但不知道如何在命令行应用程序中设置它。这必须是相同的验证密钥才能以正确的格式加密 cookie?
服务器是用asp-net mvc编写的。
var request = (HttpWebRequest)WebRequest.Create(uri);
var formsCookiePath = "/";
var cookieName = ".FormName";
var domain = "localhost";
var username = "username";
var password = "pa$$word";
var ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Today.AddYears(10),
true,
password,
formsCookiePath);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var authenticationCookie = new Cookie(
cookieName,
encryptedTicket,
formsCookiePath,
domain)
{
HttpOnly = true,
Secure = false
};
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(authenticationCookie);
request.UserAgent = "Internal downloader";
var loWebResponse = (HttpWebResponse)request.GetResponse();
更新: 根据 Zruty 的回答,我使用此示例生成身份验证 cookie:
【问题讨论】:
标签: asp.net-mvc forms-authentication