干得好.ASP.当您使用FormsAuthentication中内置的更高级别方法时,NET会为您解决这一问题,但在较低级别上,创建身份验证cookie需要这种方法.
if (Membership.ValidateUser(username, password))
{
// sometimes used to persist user roles
string userData = string.Join("|",GetCustomUserRoles());
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
username, // authenticated username
DateTime.Now, // issueDate
DateTime.Now.AddMinutes(30), // expiryDate
isPersistent, // true to persist across browser sessions
userData, // can be used to store additional user data
FormsAuthentication.FormsCookiePath); // the path for the cookie
// Encrypt the ticket using the machine key
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Add the cookie to the request to save it
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
// Your redirect logic
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
}
我不知道你为什么想在这里做些定制的事情.如果您想更改用户数据存储位置和用户身份验证方式的实现,那么最好创建一个自定义的MembershipProvider
.滚动您自己的解决方案并使用身份验证cookie意味着很有可能在您的软件中引入安全漏洞.
我不理解您的第2部分.如果您希望将用户返回到他们被弹出登录时试图访问的页面,则只需调用FormsAuthentication.GetRedirectUrl.如果您不想在这里执行任何操作,请根据需要重定向到存储在配置中的URL.
要读取FormsAuthentication cookie,通常需要在HttpModule或Global中钩住AuthenticateRequest
事件.asax并设置用户IPrinciple
上下文.
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if(authCookie != null)
{
//Extract the forms authentication cookie
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
// If caching roles in userData field then extract
string[] roles = authTicket.UserData.Split(new char[]{'|'});
// Create the IIdentity instance
IIdentity id = new FormsIdentity( authTicket );
// Create the IPrinciple instance
IPrincipal principal = new GenericPrincipal(id, roles);
// Set the context user
Context.User = principal;
}
}