说明: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. 1421 - Wavio Sequence

    题目大意:求一个序列中 先严格递增后严格递减的子序列的数目(要求这个子序列对称). 题目思路:正一遍DP,反一遍DP,因为n<=1e5,dp要把时间压缩到nlogn #include<st ...

  2. Pycharm 2018 Activation code 在线激活

    1. 下载官方 pycharm https://www.jetbrains.com/pycharm/download/ 2. 点击获取激活码 点击获取激活码 2.1 打开  hosts 文件 2.2  ...

  3. CentOS7开启防火墙及特定端口

    开启防火墙服务 以前为了方便,把防火墙都关闭了,因为现在项目都比较重要,害怕受到攻击,所以为了安全性,现在需要将防火墙开启,接下来介绍一下步骤. 1, 首先查看防火墙状态: firewall-cmd ...

  4. 统计分析与R软件-chapter2-5

    2.5 多维数组和矩阵 2.5.1 生成数组或矩阵 数组有一个特征属性叫做维数向量(dim属性),维数向量是一个元素取正整数的向量,其长度是数组的维数,比如维数向量有两个元素时数组为2维数组(矩阵). ...

  5. A Light CNN for Deep Face Representation with Noisy Labels

    承接上一篇博客.该论文思路清晰,实验充分,这里大致写一些比较不错的idea.从标题就能看出本文的主要贡献:轻量.鲁棒.利用一个轻量CNN从大规模数据且含大量噪声中来学习一个深度面部表征. 直接谈谈贡献 ...

  6. Go语言中的slice

    Go语言中的slice有点类似于Java中的ArrayList,但在使用上更加灵活,先通过下面一个小例子来体验一下如何通过一个已有的切片来产生一个新切片: func main() { slice := ...

  7. 利用 git format-patch 和 git send-email 把修改的 patch 文件发送给 ffmpeg-devel

    1. 下载源码git clone https://git.ffmpeg.org/ffmpeg.git 2. 设置 git 用户的邮箱和姓名git config --global user.email ...

  8. 利用HBuilder将vue项目打包成移动端app

    事先准备,开发完成的web app项目(也可以利用vue-cli脚手架构建vue模板项目),npm run dev可以正常预览的项目 1,将项目目录下config文件内index.js中assetsP ...

  9. 持续集成之④:GitLab触发jenkins构建项目

    持续集成之④:GitLab触发jenkins构建项目 一:目的为在公司的测试环境当中一旦开发向gitlab仓库提交成功代码,gitlab通知jenkins进行构建项目.代码质量测试然后部署至测试环境, ...

  10. Windows Server 2008 R2 报错事件ID:10之WMI报错

    问题描述: Details -Event filter with query "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHE ...