<fieldset><legend>用户状态</legend><form action="<%= Request.RawUrl %>" method="post">
<% if( Request.IsAuthenticated ) { %>
当前用户已登录,登录名:<%= Context.User.Identity.Name.HtmlEncode() %> <br />
<input type="submit" name="Logon" value="退出" />
<% } else { %>
<b>当前用户还未登录。</b>
<% } %>
</form></fieldset>
<fieldset><legend>普通登录</legend><form action="<%= Request.RawUrl %>" method="post"> 登录名:<input type="text" name="loginName" style="width: 200px" value="Fish" /> <input type="submit" name="NormalLogin" value="登录" /> </form></fieldset>
public void Logon()
{
FormsAuthentication.SignOut();
}
public void NormalLogin()
{
// -----------------------------------------------------------------
// 注意:演示代码为了简单,这里不检查用户名与密码是否正确。
// -----------------------------------------------------------------
string loginName = Request.Form["loginName"];
if( string.IsNullOrEmpty(loginName) )
return;
FormsAuthentication.SetAuthCookie(loginName, true);
TryRedirect();
}
<location path="MyInfo.aspx"> <system.web> <authorization> <deny users="?"/> </authorization> </system.web> </location>
<location path="Admin"> <system.web> <authorization> <allow roles="Admin"/> <deny users="*"/> </authorization> </system.web> </location>
<authorization> <deny users="?"/> </authorization>
<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>FormsAuthentication DEMO - http://www.cnblogs.com/fish-li/</title>
<link type="text/css" rel="Stylesheet" href="css/StyleSheet.css" />
</head>
<body>
<fieldset><legend>普通登录</legend><form action="<%= Request.RawUrl %>" method="post">
登录名:<input type="text" name="loginName" style="width: 200px" value="Fish" />
<input type="submit" name="NormalLogin" value="登录" />
</form></fieldset>
<fieldset><legend>用户状态</legend><form action="<%= Request.RawUrl %>" method="post">
<% if( Request.IsAuthenticated ) { %>
当前用户已登录,登录名:<%= Context.User.Identity.Name.HtmlEncode() %> <br />
<% var user = Context.User as MyFormsPrincipal<UserInfo>; %>
<% if( user != null ) { %>
<%= user.UserData.ToString().HtmlEncode() %>
<% } %>
<input type="submit" name="Logon" value="退出" />
<% } else { %>
<b>当前用户还未登录。</b>
<% } %>
</form></fieldset>
<p id="hideText"><i>不应该显示的文字</i></p>
<script type="text/javascript" src="js/JScript.js"></script>
</body>
</html>
document.getElementById("hideText").setAttribute("style", "display: none");
<?xml version="1.0"?> <configuration> <system.web> <authorization> <allow users="*"/> </authorization> </system.web> </configuration>
<authentication mode="Forms" > <forms cookieless="UseCookies" name="LoginCookieName" loginUrl="~/Default.aspx"></forms> </authentication>
public static FormsAuthenticationTicket RenewTicketIfOld(FormsAuthenticationTicket tOld)
{
// 这段代码是意思是:当指定的超时时间逝去大半时将更新FormsAuthenticationTicket对象。
if( tOld == null )
return null;
DateTime now = DateTime.Now;
TimeSpan span = (TimeSpan)(now - tOld.IssueDate);
TimeSpan span2 = (TimeSpan)(tOld.Expiration - now);
if( span2 > span )
return tOld;
return new FormsAuthenticationTicket(tOld.Version, tOld.Name,
now, now + (tOld.Expiration - tOld.IssueDate),
tOld.IsPersistent, tOld.UserData, tOld.CookiePath);
}
Request.IsAuthenticated可以告诉我们当前请求是否已经过身份验证,我们来看一下这个属性是如何实现的:
public bool IsAuthenticated
{
get
{
return (((this._context.User != null)
&& (this._context.User.Identity != null))
&& this._context.User.Identity.IsAuthenticated);
}
}
// 为当前 HTTP 请求获取或设置安全信息。
//
// 返回结果:
// 当前 HTTP 请求的安全信息。
public IPrincipal User { get; set; }
public class MyFormsPrincipal<TUserData> : IPrincipal
where TUserData : class, new()
{
private IIdentity _identity;
private TUserData _userData;
public MyFormsPrincipal(FormsAuthenticationTicket ticket, TUserData userData)
{
if( ticket == null )
throw new ArgumentNullException("ticket");
if( userData == null )
throw new ArgumentNullException("userData");
_identity = new FormsIdentity(ticket);
_userData = userData;
}
public TUserData UserData
{
get { return _userData; }
}
public IIdentity Identity
{
get { return _identity; }
}
public bool IsInRole(string role)
{
// 把判断用户组的操作留给UserData去实现。
IPrincipal principal = _userData as IPrincipal;
if( principal == null )
throw new NotImplementedException();
else
return principal.IsInRole(role);
}
public class UserInfo : IPrincipal
{
public int UserId;
public int GroupId;
public string UserName;
// 如果还有其它的用户信息,可以继续添加。
public override string ToString()
{
return string.Format("UserId: {0}, GroupId: {1}, UserName: {2}, IsAdmin: {3}",
UserId, GroupId, UserName, IsInRole("Admin"));
}
#region IPrincipal Members
[ScriptIgnore]
public IIdentity Identity
{
get { throw new NotImplementedException(); }
}
public bool IsInRole(string role)
{
if( string.Compare(role, "Admin", true) == 0 )
return GroupId == 1;
else
return GroupId > 0;
}
#endregion
}
/// <summary>
/// 执行用户登录操作
/// </summary>
/// <param name="loginName">登录名</param>
/// <param name="userData">与登录名相关的用户信息</param>
/// <param name="expiration">登录Cookie的过期时间,单位:分钟。</param>
public static void SignIn(string loginName, TUserData userData, int expiration)
{
if( string.IsNullOrEmpty(loginName) )
throw new ArgumentNullException("loginName");
if( userData == null )
throw new ArgumentNullException("userData");
// 1. 把需要保存的用户数据转成一个字符串。
string data = null;
if( userData != null )
data = (new JavaScriptSerializer()).Serialize(userData);
// 2. 创建一个FormsAuthenticationTicket,它包含登录名以及额外的用户数据。
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
2, loginName, DateTime.Now, DateTime.Now.AddDays(1), true, data);
// 3. 加密Ticket,变成一个加密的字符串。
string cookieValue = FormsAuthentication.Encrypt(ticket);
// 4. 根据加密结果创建登录Cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue);
cookie.HttpOnly = true;
cookie.Secure = FormsAuthentication.RequireSSL;
cookie.Domain = FormsAuthentication.CookieDomain;
cookie.Path = FormsAuthentication.FormsCookiePath;
if( expiration > 0 )
cookie.Expires = DateTime.Now.AddMinutes(expiration);
HttpContext context = HttpContext.Current;
if( context == null )
throw new InvalidOperationException();
// 5. 写登录Cookie
context.Response.Cookies.Remove(cookie.Name);
context.Response.Cookies.Add(cookie);
}
<fieldset><legend>包含【用户信息】的自定义登录</legend> <form action="<%= Request.RawUrl %>" method="post"> <table border="0"> <tr><td>登录名:</td> <td><input type="text" name="loginName" style="width: 200px" value="Fish" /></td></tr> <tr><td>UserId:</td> <td><input type="text" name="UserId" style="width: 200px" value="78" /></td></tr> <tr><td>GroupId:</td> <td><input type="text" name="GroupId" style="width: 200px" /> 1表示管理员用户 </td></tr> <tr><td>用户全名:</td> <td><input type="text" name="UserName" style="width: 200px" value="Fish Li" /></td></tr> </table> <input type="submit" name="CustomizeLogin" value="登录" /> </form></fieldset>
public void CustomizeLogin()
{
// -----------------------------------------------------------------
// 注意:演示代码为了简单,这里不检查用户名与密码是否正确。
// -----------------------------------------------------------------
string loginName = Request.Form["loginName"];
if( string.IsNullOrEmpty(loginName) )
return;
UserInfo userinfo = new UserInfo();
int.TryParse(Request.Form["UserId"], out userinfo.UserId);
int.TryParse(Request.Form["GroupId"], out userinfo.GroupId);
userinfo.UserName = Request.Form["UserName"];
// 登录状态100分钟内有效
MyFormsPrincipal<UserInfo>.SignIn(loginName, userinfo, 100);
TryRedirect();
}
<fieldset><legend>用户状态</legend><form action="<%= Request.RawUrl %>" method="post">
<% if( Request.IsAuthenticated ) { %>
当前用户已登录,登录名:<%= Context.User.Identity.Name.HtmlEncode() %> <br />
<% var user = Context.User as MyFormsPrincipal<UserInfo>; %>
<% if( user != null ) { %>
<%= user.UserData.ToString().HtmlEncode() %>
<% } %>
<input type="submit" name="Logon" value="退出" />
<% } else { %>
<b>当前用户还未登录。</b>
<% } %>
</form></fieldset>
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
MyFormsPrincipal<UserInfo>.TrySetUserInfo(app.Context);
}
TrySetUserInfo的实现代码:
/// <summary>
/// 根据HttpContext对象设置用户标识对象
/// </summary>
/// <param name="context"></param>
public static void TrySetUserInfo(HttpContext context)
{
if( context == null )
throw new ArgumentNullException("context");
// 1. 读登录Cookie
HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
if( cookie == null || string.IsNullOrEmpty(cookie.Value) )
return;
try {
TUserData userData = null;
// 2. 解密Cookie值,获取FormsAuthenticationTicket对象
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
if( ticket != null && string.IsNullOrEmpty(ticket.UserData) == false )
// 3. 还原用户数据
userData = (new JavaScriptSerializer()).Deserialize<TUserData>(ticket.UserData);
if( ticket != null && userData != null )
// 4. 构造我们的MyFormsPrincipal实例,重新给context.User赋值。
context.User = new MyFormsPrincipal<TUserData>(ticket, userData);
}
catch { /* 有异常也不要抛出,防止攻击者试探。 */ }
}
<machineKey decryption="Auto" [Auto | DES | 3DES | AES] decryptionKey="AutoGenerate,IsolateApps" [String] />
private static readonly string MyInfoPageUrl = "http://localhost:51855/MyInfo.aspx";
static void Main(string[] args)
{
// 这个调用得到的结果其实是default.aspx页面的输出,并非MyInfo.aspx
HttpWebRequest request = MyHttpClient.CreateHttpWebRequest(MyInfoPageUrl);
string html = MyHttpClient.GetResponseText(request);
if( html.IndexOf("<span>Fish</span>") > 0 )
Console.WriteLine("调用成功。");
else
Console.WriteLine("页面结果不符合预期。");
}
private static readonly string LoginUrl = "http://localhost:51855/default.aspx";
private static readonly string MyInfoPageUrl = "http://localhost:51855/MyInfo.aspx";
static void Main(string[] args)
{
// 创建一个CookieContainer实例,供多次请求之间共享Cookie
CookieContainer cookieContainer = new CookieContainer();
// 首先去登录页面登录
MyHttpClient.HttpPost(LoginUrl, "NormalLogin=aa&loginName=Fish", cookieContainer);
// 此时cookieContainer已经包含了服务端生成的登录Cookie
// 再去访问要请求的页面。
string html = MyHttpClient.HttpGet(MyInfoPageUrl, cookieContainer);
if( html.IndexOf("<span>Fish</span>") > 0 )
Console.WriteLine("调用成功。");
else
Console.WriteLine("页面结果不符合预期。");
// 如果还要访问其它的受限页面,可以继续调用。
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有