说明: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(,); //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 = ; i < ; i++)
{
vCode += strArry[r.Next(strArry.Length)];
}
//05 开始绘制
g.DrawString(vCode,new Font (new FontFamily("宋体"),),new SolidBrush(Color.Red),,);
//06 保存
bm.Save(context.Response.OutputStream,ImageFormat.Jpeg);
//07 将验证码的值写入Session中,方便以后校验
context.Session["ValidateCode"] = vCode;
} public bool IsReusable
{
get
{
return false;
}
}
}
}

ValidateCode 验证码

<%@ 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") + '');
});
})
</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="" height="" border="" align="center" cellpadding="" cellspacing="" background="./网站管理后台登录_files/login_bg.jpg">
<tbody>
<tr>
<td width="">
<img src="./网站管理后台登录_files/login_leftbg.jpg" width="" height=""></td>
<td width="" valign="top">
<table width="100%" border="" cellspacing="" cellpadding="">
<tbody>
<tr>
<td width="49%" valign="bottom">
<table width="90%" border="" align="center" cellpadding="" cellspacing="">
<tbody>
<tr>
<td height="" valign="top" class="login_text">
<div align="left">
网站后台管理系统
</div>
</td>
</tr>
<tr>
<td>
<div align="right">
<img src="./网站管理后台登录_files/login_img.jpg" width="" height=""></div>
</td>
</tr>
</tbody>
</table>
</td>
<td width="2%">
<img src="./网站管理后台登录_files/login_line.jpg" width="" height=""></td>
<td width="49%">
<div align="right">
<table width="" border="" cellspacing="" cellpadding="">
<tbody>
<tr>
<td>
<img src="./网站管理后台登录_files/login_tit.jpg" width="" height=""></td>
</tr>
<tr>
<td>
<table width="100%" border="" cellspacing="" cellpadding="">
<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">密&nbsp;码:</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;">&nbsp;
<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="" id="txtCode" class="form2" style="height: 15px;"></span>
</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td align="center">
<table width="100%" border="" cellspacing="" cellpadding="">
<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="">
<img src="./网站管理后台登录_files/login_rigbg.jpg" width="" height=""></td>
</tr>
</tbody>
</table>
</div>
</form> </body>
</html>

aspx

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 }
}

aspx.cs

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+"登录本系统");
}
}
}
}

ShowUserInfo

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");
}
}
}
}

NewsCommon===CheckSession

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+"登录本系统"); }
}
}

ShowUserInfo

1.6 另外添加"记住我"和退出功能==多值cookie 41行和95行

 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();
public 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)
{
//01 登录成功,创建session
Session["UserInfo"] = userInfo;
//02 判断是否选中"记住我1周"的cookie判断
//写入cookie====多值cookie
if (Request["Remember"] == "on")
{
Response.Cookies["userInfo"]["UserId"] = userInfo.UserId.ToString();
Response.Cookies["userInfo"]["UserName"] = userInfo.UserName;
Response.Cookies["userInfo"]["UserPwd"] = userInfo.UserPwd;
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(); }
//删除cookie
if (Request["Forget"] == "on")
{
Session["UserInfo"] = null;
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(-);
Response.Write("退出成功,Session值已清除,cookie值已清除");
//程序不再往下走
Response.End(); }
//03跳转页面
Response.Redirect("ShowUserInfo.aspx");
}
else
{
Response.Write("密码错误");
}
}
else
{
Response.Write("用户不存在");
} }
else
{
Response.Write("用户名为数字");
} }
else
{
Response.Write("验证码不正确");
}
}
else
{
//get 请求
//01 判断Session值是否存在
if ( Session["UserInfo"]!= null)
{
//如果 Session["UserInfo"]存在,直接进行跳转
Response.Redirect("ShowUserInfo.aspx");
}
//02 判断Cookie值是否存在
if ((Request.Cookies["userInfo"]) != null)
{
userInfo.UserId = Convert.ToInt32(Request.Cookies["userInfo"]["UserId"]);
userInfo.UserName = Request.Cookies["userInfo"]["UserName"];
userInfo.UserPwd = Request.Cookies["userInfo"]["UserPwd"];
}
}
} #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 }
}

aspx.cs

<%@ 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") + '');
});
})
</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="" height="" border="" align="center" cellpadding="" cellspacing="" background="./网站管理后台登录_files/login_bg.jpg">
<tbody>
<tr>
<td width="">
<img src="./网站管理后台登录_files/login_leftbg.jpg" width="" height=""></td>
<td width="" valign="top">
<table width="100%" border="" cellspacing="" cellpadding="">
<tbody>
<tr>
<td width="49%" valign="bottom">
<table width="90%" border="" align="center" cellpadding="" cellspacing="">
<tbody>
<tr>
<td height="" valign="top" class="login_text">
<div align="left">
网站后台管理系统
</div>
</td>
</tr>
<tr>
<td>
<div align="right">
<img src="./网站管理后台登录_files/login_img.jpg" width="" height="">
</div>
</td>
</tr>
</tbody>
</table>
</td>
<td width="2%">
<img src="./网站管理后台登录_files/login_line.jpg" width="" height=""></td>
<td width="49%">
<div align="right">
<table width="" border="" cellspacing="" cellpadding="">
<tbody>
<tr>
<td>
<img src="./网站管理后台登录_files/login_tit.jpg" width="" height=""></td>
</tr>
<tr>
<td>
<table width="100%" border="" cellspacing="" cellpadding="">
<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" value="<%=userInfo.UserId %>" class="form2" style="height: 15px; width: 140px;">
</span>
</div>
</td>
</tr>
<tr>
<td>
<div align="left">密&nbsp;码:</div>
</td>
<td>
<div align="left">
<span class="style1">
<input name="txtPassword" type="password" id="txtPassword" value="<%=userInfo.UserPwd %>" 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;">&nbsp;
<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="" id="txtCode" class="form2" style="height: 15px;"></span>
</div>
</td> </tr>
<tr>
<td>
<div align="left">
<input type="checkbox" id="Forget" name="Forget" />退出 </div>
</td>
<td>
<div align="left">
<input type="checkbox" id="Remember" name="Remember" />记住我1周</div> </td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td align="center">
<table width="100%" border="" cellspacing="" cellpadding="">
<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="">
<img src="./网站管理后台登录_files/login_rigbg.jpg" width="" height=""></td>
</tr>
</tbody>
</table>
</div>
</form> </body>
</html>

aspx

步步为营-76-用户登录(Session+Cookie)的更多相关文章

  1. 用户登录之cookie信息安全一二事

    大家都知道用户登陆后,用户信息一般会选择保存在cookie里面,因为cookie是保存客户端, 并且cookie可以在客户端用浏览器自由更改,这样将会造成用户cookie存在伪造的危险,从而可能使伪造 ...

  2. requests保持登录session ,cookie 和 token

    一.request提供了一个一个叫做session的类,来实现客户端和服务端的会话保持 # coding:utf-8 import requests url = "https://passp ...

  3. onethink中的用户登录session签名

    用户登录签名问题,即防止伪造登录session,增加一个用户登录数组的加密签名 onethink的登录控制,先调用UC表中(UC表也是存储在网站或本地的数据库中的),确认登录信息.如果UC表登录成功, ...

  4. V5.7_UTF8_SP1、SP2---任意前台用户登录(cookie伪造)

    漏洞触发点在include/memberlogin.class.php中的MemberLogin类中的登录校验函数 可以看到M_ID参数是由GetNum(GetCookie("DedeUse ...

  5. Vue Abp vNext用户登录(Cookie)

    因为Abp vNext没找到Vue的模板,网上也没找到相关vNext的例子,只能自己试着写写,asp.net core abp vue都是刚学不久,所以很粗糙也可能有错误的地方,如果您看到请指正,谢谢 ...

  6. MVC 自定义特性(验证用户登录session是否已经过期)

    新建一个类 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] publ ...

  7. 步步为营-81-HttpModule(再谈Session)

    说明:session用于记录数据信息并存放在服务器内存中,但是存在一些问题.例如当使用服务器集群是会出现session丢失等情况.虽然微软提供了一些解决方案(Session进程外存储,或者存到数据库中 ...

  8. Session, Cookie区别

    答: 1.Session由应用服务器维护的一个服务器端的存储空间:Cookie是客户端的存储空间,由浏览器维护. 2.用户可以通过浏览器设置决定是否保存Cookie,而不能决定是否保存Session, ...

  9. session,cookie的理解(总结)

    会话(Session)跟踪是Web程序中常用的技术,用来跟踪用户的整个会话.常用的会话跟踪技术是Cookie与Session.Cookie通过在客户端记录信息确定用户身份,Session通过在服务器端 ...

随机推荐

  1. 20165337岳源 预备作业3:Linux安装及命令入门

    安装虚拟机 按照基于VirtualBox虚拟机安装Ubuntu图文教程的步骤安装虚拟机,遇到的问题通过同学的帮助也得到了解决.例如:虚拟机无法选择64位系统. 常用的Linux命令 Tab 补全命令. ...

  2. poi读取Excel模板并修改模板内容与动态的增加行

    有时候我们可能遇到相当复杂的excel,比如表头的合并等操作,一种简单的方式就是直接代码合并(浪费时间),另一种就是写好模板,动态的向模板中增加行和修改指定单元格数据. 1.一个简单的根据模板shee ...

  3. webstorm的快捷键总结

    ctrl+shift+f 可以在项目和模块中的文件中查找特定字符串 shift键连续敲一下,可以在项目和模块中查找特定的文件 ctrl+d  复制当前行并粘贴到下一行 ctrl+shift+上下方向键 ...

  4. MySQL log_slave_updates 参数【转】

    说明:最近部署了mysql的集群环境,详细如下M01和M02为主主复制,M01和R01为主从复制:在测试的过程中发现了以下问题: 1.M01和M02的主主复制是没有问题的(从M01写入数据能同步到M0 ...

  5. Python3学习笔记30-datetime模块

    datetime是Python处理日期和时间的标准库 获取当前的日期和时间 from datetime import datetime now = datetime.now() print(now) ...

  6. C#基础巩固之属性

    平常写代码,类中最长用到的字段,属性,方法.虽然经常用属性,但是对属性的认知只是停留在{get;set;}上,也知道可以逻辑判断,只读什么的,没有深入研究: 此篇随笔用来做做属性的文章,加深下认知,文 ...

  7. 移动硬盘和u盘的区别

    移动硬盘和U盘都属于便携性存储器,用于计算机之间的数据交换.但移动硬盘和U盘的区别还是非常大的,包括内部构造.容量以及整体外观上. 移动硬盘又分为机械移动硬盘和固态移动硬盘两种,主要区别在于内置的存储 ...

  8. 链接器link.exe 编译器cl.exe 资源编译器rc.exe

    原文地址:https://blog.csdn.net/biggbang/article/details/24433065 1.cl.exe文件是Visual C\C++的编译器,它将程序源代码文件编译 ...

  9. zabbix添加对centos系统cpu使用率百分比的监控

    cpu使用率key: system.cpu.util[] 在grafana现实的时候配置,单位选择percent(0-100),范围0-100

  10. 1.ROS启动小乌龟

        启动turtlesim 在三个不同的终端中分别执行如下三个指令 roscore rosrun turtlesim turtlesim_node rosrun turtlesim turtle_ ...