步步为营-76-用户登录(Session+Cookie)
Posted 逍遥小天狼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了步步为营-76-用户登录(Session+Cookie)相关的知识,希望对你有一定的参考价值。
说明:cookie是保存在浏览器的.Session是存储在服务器的
1 同样UI页面还是web前端提供
1.1 首先,经过验证码校验:将系统产生的验证码放入到Session中,然后取Session值
注意几点 1:放入Session时需要实现 IRequiresSessionState接口(因为是ashx,一般处理程序)
2:使用前先判断是否为空
3:用完验证码Session值注销(否则会有漏洞)
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Web; using System.Drawing.Imaging; using System.Web.SessionState; namespace _06_图片处理 { /// <summary> /// ValidateCode 的摘要说明 /// </summary> public class ValidateCode : IHttpHandler,IRequiresSessionState { public void ProcessRequest(HttpContext context) { //01 验证码是图片,所以修改Type context.Response.ContentType = "image/jpeg"; //02 创建画布 Bitmap bm = new Bitmap(70,30); //03 创建绘图工具 Graphics g = Graphics.FromImage(bm); //03-01 设置背景色 g.Clear(Color.Green); //04 准备绘制 string strArry = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string vCode = string.Empty; Random r = new Random (); for (int i = 0; i < 4; i++) { vCode += strArry[r.Next(strArry.Length)]; } //05 开始绘制 g.DrawString(vCode,new Font (new FontFamily("宋体"),20),new SolidBrush(Color.Red),0,0); //06 保存 bm.Save(context.Response.OutputStream,ImageFormat.Jpeg); //07 将验证码的值写入Session中,方便以后校验 context.Session["ValidateCode"] = vCode; } public bool IsReusable { get { return false; } } } }
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="_04_用户登录_cookie_Session_.Login" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> <title>网站管理后台登录 </title> <script src="Script/jquery-1.7.1.min.js"></script> <script> $(function () { $("#changeCode").click(function () { $(\'#Image1\').attr("src", $(\'#Image1\').attr("src") + \'1\'); }); }) </script> <link href="./网站管理后台登录_files/style.css" rel="stylesheet" type="text/css"> <style type="text/css"> <!-- body { margin-top: 150px; } --> </style> </head> <body> <form name="form1" method="post" action="" id="form1"> <div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTk5MTEyNDkyMmQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFCGJ0bkxvZ2luDPRvv9LGLqiVqStAd5fp6Kr+5/0="> </div> <div> <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBQLemczKAwLd+/CSBQK1qbSRCwLChPzDDQKC3IeGDDY6Y328gLlSy6Sd5458JxEqkhYO"> </div> <div> <table width="549" height="287" border="0" align="center" cellpadding="0" cellspacing="0" background="./网站管理后台登录_files/login_bg.jpg"> <tbody> <tr> <td width="23"> <img src="./网站管理后台登录_files/login_leftbg.jpg" width="23" height="287"></td> <td width="503" valign="top"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td width="49%" valign="bottom"> <table width="90%" border="0" align="center" cellpadding="0" cellspacing="0"> <tbody> <tr> <td height="100" valign="top" class="login_text"> <div align="left"> 网站后台管理系统 </div> </td> </tr> <tr> <td> <div align="right"> <img src="./网站管理后台登录_files/login_img.jpg" width="104" height="113"></div> </td> </tr> </tbody> </table> </td> <td width="2%"> <img src="./网站管理后台登录_files/login_line.jpg" width="6" height="287"></td> <td width="49%"> <div align="right"> <table width="223" border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td> <img src="./网站管理后台登录_files/login_tit.jpg" width="223" height="30"></td> </tr> <tr> <td> <table width="100%" border="0" cellspacing="10" cellpadding="0"> <tbody> <tr> <td width="28%"> <div align="left">用户名:</div> </td> <td width="72%"> <div align="left"> <span class="style1"> <input name="txtClientID" type="text" id="txtClientID" class="form2" style="height: 15px; width: 140px;"> </span> </div> </td> </tr> <tr> <td> <div align="left">密 码:</div> </td> <td> <div align="left"> <span class="style1"> <input name="txtPassword" type="password" id="txtPassword" class="form2" style="height: 15px; width: 140px;"></span> </div> </td> </tr> <tr> <td> <div align="left">验证码:</div> </td> <td> <div align="left"> <img id="Image1" src="./网站管理后台登录_files/ValidateCode.ashx?1" style="border-width: 0px;"> <a href="#" id="changeCode">换一张</a> </div> </td> </tr> <tr> <td> <div align="left">验证码:</div> </td> <td> <div align="left"> <span class="style1"> <input name="txtCode" type="text" size="8" id="txtCode" class="form2" style="height: 15px;"></span> </div> </td> </tr> </tbody> </table> </td> </tr> <tr> <td align="center"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td> <div align="center"><a href="http://www.800kb.com/ClientManager/#"></a></div> </td> <td> <div align="center"> <input type="image" name="btnLogin" id="btnLogin" src="./网站管理后台登录_files/login_menu2.jpg" style="border-width: 0px;"><a href="Login.aspx.cs"></a> </div> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </div> </td> </tr> </tbody> </table> </td> <td width="23"> <img src="./网站管理后台登录_files/login_rigbg.jpg" width="23" height="287"></td> </tr> </tbody> </table> </div> </form> </body> </html>
using NewsBLL; using NewsModel; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace _04_用户登录_cookie_Session_ { public partial class Login : System.Web.UI.Page { UserInfoBll bll = new UserInfoBll(); UserInfo userInfo = new UserInfo(); protected void Page_Load(object sender, EventArgs e) { //01 判断get请求还是post请求 if (Request["txtCode"] != null) { //02 检查验证码是否正确 if (CheckValidateCode()) { //03 检查用户名 密码是否正确 //03-01 获取用户名和密码 string userName = Request["txtClientID"]; string userPwd = Request["txtPassword"]; //03-02 根据用户名获取用户信息 int userId; if (int.TryParse(userName, out userId)) { userInfo = bll.GetUserInfoByUserId(userId); if (userInfo != null) { if (userInfo.UserPwd == userPwd) { Response.Write("登录成功"); } else { Response.Write("密码错误"); } } else { Response.Write("用户不存在"); } } else { Response.Write("用户名为数字"); } } else { Response.Write("验证码不正确"); } } } #region 01 检查验证码 private bool CheckValidateCode() { //01-01 获取验证码的值,将系统产生的验证码放入到Session中,然后取Session值 //注意两点 1:放入Session时需要实现 IRequiresSessionState接口(因为是ashx,一般处理程序) //注意两点 2:用完验证码Session值注销(否则会有漏洞) if (Session["ValidateCode"] == null) { return false; } string validateCode = Session["ValidateCode"].ToString(); //01-02 获取文本框中输入的值 string vCode = Request["txtCode"]; //01-03 判断是否相等 if (vCode.Equals(validateCode, StringComparison.InvariantCultureIgnoreCase)) { //使用后注销session值 Session["ValidateCode"] = null; return true; } else { return false; } } #endregion } }
1.2 如果登录成功,创建session,跳转到ShowUserInfo界面
Session["UserInfo"] = userInfo;
Response.Redirect("ShowUserInfo.aspx");
1.3 为了防止用户直接通过地址访问,所以进入ShowUserInfo等界面时需要判断Session值
using NewsModel; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace _04_用户登录_cookie_Session_ { public partial class ShowUserInfo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //判断Session["userInfo"]是否为空 if (Session["userInfo"] == null) { Response.Redirect("Login.aspx"); } else { Response.Write("欢迎" + ((UserInfo)Session["userInfo"]).UserName+"登录本系统"); } } } }
1.4 但是如果以后每个页面都需要做同样的验证,会出现大量重复代码,而且一旦需求变更,不利于系统维护,
封装一个类,继承Page类=>添加Page_Init(object sender,EventArgs e)方法 进行Session校验.
注意:Page_Init 这里用到了页面生命周期大致分为:页请求=>启动=>初始化=>加载=>执行=>呈现=>卸载 等周期
我们在aspx.cs 中写的代码是在加载阶段Page_Load();而Page_Init是在初始化阶段.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.UI; namespace NewsCommon { public class CheckSession:Page { public void Page_Init(object sender,EventArgs e) { //判断Session["userInfo"]是否为空 if (Session["userInfo"] == null) { Response.Redirect("Login.aspx"); } } } }
1.5 同时,ShowUserInfo页面继承CheckSession
using NewsCommon; using NewsModel; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace _04_用户登录_cookie_Session_ { public partial class ShowUserInfo : CheckSession { protected void Page_Load(object sender, EventArgs e) { //判断Session["userInfo"]是否为空==通过NewsCommon中的CheckSession校验 Response.Write("欢迎" + ((UserInfo)Session["userInfo"]).UserName+"登录本系统"); } } }
1.6 另外添加"记住我"和退出功能==多值cookie 41行和95行
1 using NewsBLL; 2 using NewsModel; 3 using System; 4 using System.Collections.Generic; 5 using System.Linq; 6 using System.Web; 7 using System.Web.UI; 8 using System.Web.UI.WebControls; 9 10 namespace _04_用户登录_cookie_Session_ 11 { 12 public partial class Login : System.Web.UI.Page 13 { 14 UserInfoBll bll = new UserInfoBll(); 15 public UserInfo userInfo = new UserInfo(); 16 protected void Page_Load(object sender, EventArgs e) 17 { 18 //01 判断get请求还是post请求 19 if (Request["txtCode"] != null) 20 { 21 //02 检查验证码是否正确 22 if (CheckValidateCode()) 23 { 24 //03 检查用户名 密码是否正确 25 //一步步学Metal图形引擎10-《BRDF:Cook-Torrance光照模型》