说明: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. 20165234 《Java程序设计》第七周学习总结

    第七周学习总结 教材内容学习 第十一章 JDBC与MySQL数据库 连接数据库: 1. 下载JDBC-MySQL数据库驱动 2. 加载JDBC-MySQL数据库驱动 3. 连接数据库 条件与排序查询: ...

  2. nodejs -Router

    Node 用 request 事件来处理请求响应,事件内使用分支语句处理不同路径的请求,而 Express 封装了这些操作,使得代码简洁优雅 但如果请求路径变多,都写在 app.js 文件里的话,就会 ...

  3. 2018 codejam kickstart H轮

    被第一题傻逼题卡了很久……好的我也是个傻逼 倒在了最后一题 本来以为小数据过了就能过大数据 结果下载了大数据 发现怎么输出了好多个零 调代码过程中超时了 结束后重新提交了一下 果然是不通过的 A 题目 ...

  4. 3.2. 使​​​​​​​用​​​​​​​ CPUFREQ 调​​​​​​​节​​​​​​​器​​​​​​​【转】

    转自:https://access.redhat.com/documentation/zh-cn/red_hat_enterprise_linux/6/html/power_management_gu ...

  5. Nginx 测试环境配置,留作笔记使用

    Nginx 测试环境配置,留做笔记 以下全是配置文件的配置,如果有疑问还请移步Nginx官网参考官方文档. 环境: [root@CentOS6-M01 conf]# cat /etc/redhat-r ...

  6. cisco和华为的设备如何设置命令不分页显示

    作者:邓聪聪 为了登陆设备查看信息没有分页,cisco和华为的设备上可以设置不分页显示 Cisco: > terminal length HUAWEI / H3C: > user-inte ...

  7. vc++高级班之多线程篇[7]---线程间的同步机制②

    //示例代码: CStringArray g_ArrString; UINT __cdecl ThreadProc(LPVOID lpParameter) {  int startIdx = (int ...

  8. python操作Excel的库openpyxl

    http://openpyxl.readthedocs.io/en/default/tutorial.html 这里先上该库的文档镇文. 1,遇到合并后的单元格信息读取的问题,通过使用cell中off ...

  9. 转载:HBuilder常用快捷键

    原文:http://www.cnblogs.com/DCL1314/p/8625110.html HBuilder常用快捷键 1.文件 新建 Ctrl + N 关闭 Ctrl + F4 全部关闭 Ct ...

  10. POJ 3368

    题意: 给你一组数列, 查询区间内有出现次数最多的数的频数 RMQ , 对于一个区间, 分为两部分, 从  L 开始连续到  T  , T + 1 到  R 显然 答案为  MAX (T – L + ...