惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
S
Schneier on Security
The Hacker News
The Hacker News
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
I
Intezer
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Schneier on Security
Schneier on Security
Security Latest
Security Latest
AWS News Blog
AWS News Blog
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog
有赞技术团队
有赞技术团队
博客园 - 叶小钗
The Last Watchdog
The Last Watchdog
O
OpenAI News
月光博客
月光博客
Hacker News: Ask HN
Hacker News: Ask HN
阮一峰的网络日志
阮一峰的网络日志
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Latest news
Latest news
P
Palo Alto Networks Blog
Last Week in AI
Last Week in AI
M
MIT News - Artificial intelligence
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Apple Machine Learning Research
Apple Machine Learning Research
U
Unit 42
PCI Perspectives
PCI Perspectives
博客园 - 聂微东
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
Forbes - Security
Forbes - Security
H
Heimdal Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Troy Hunt's Blog
博客园 - 三生石上(FineUI控件)
Application and Cybersecurity Blog
Application and Cybersecurity Blog
罗磊的独立博客
WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security

文章列表 - 她和她的猫

使用小鹤双拼一个月 折腾 Hugo PaperMod 主题 去长鹿旅游休博园 1Password 自动化登录堡垒机 深入 Hyperf:Inject 注解是如何工作的? 译|理解容器镜像层 使用 Rust 实现高性能预写日志(Write Ahead Log) 译|使用 Linux 命名空间隔离系统 深入 Hyperf:HTTP 服务是如何处理请求的? Linux 文件权限学习笔记 译|了解 Bitcask:基于日志结构的 KV 存储引擎 还原 SM2 压缩公钥的几种方法 深入 Hyperf:HTTP 服务启动时发生了什么? 一次 Hyperf 注解失效问题分析 将博客迁移到又拍云 译|PHP 7 新的 Hashtable 实现 排查 ES 查询问题:深入了解 json_encode() 函数 浅析 Redlock 分布式锁实现原理 Yar 源码阅读笔记:RPC 服务端 Yar 源码阅读笔记:客户端的并行调用 Yar 源码阅读笔记:客户端的同步调用 Yar 源码阅读笔记:数据传输模块 Yar 源码阅读笔记:消息编码模块 Yar 源码阅读笔记:RPC 通信协议 Yar 源码阅读笔记:开篇 PHP 8 新特性介绍 基于 OpenSSL 实现国密 SM4 加解密 PHP 源码阅读笔记:编译与调试 PHP 什么是惊群问题 大端模式和小端模式 基于 GitHub Actions 定时推送网址到百度站长平台 聊聊五种 I/O 模型 Workerman 源码分析:文件上传 浅入浅出 HTTP 协议 PHP 网络编程:构建 MySQL 蜜罐获取攻击者微信 ID 使用 Workerman 接入 Bilibili 直播弹幕协议 使用 GitHub Actions 自动部署 Hexo 什么是二进制安全 【转载】PHP 程序员进阶之路 优化 Workerman 检查主进程是否存活的逻辑 基于 Redis 实现分布式锁 《PHP 实现 Base64 编码/解码》笔记 PHP 多进程下载必应壁纸 基于 Redis 实现延迟队列 【转载】PHP 实现 Base64 编码/解码 使用 MySQL FIELD() 函数自定义排序规则 Laravel 的 Facades 实现原理 C语言单链表实现约瑟夫环 数据结构学习笔记:顺序栈和链栈(C语言) 使用 QueryList + Redis 下载壁纸 在 Laravel 登录/注册中使用 mews/captcha 扩展包 使用 mews/captcha 扩展包为 Laravel 应用添加图片验证码 给 YOURLS 短网址系统编写插件《批量生成短网址》 给 YOURLS 短网址系统编写插件《Hello World!》 PHP 7.1 使用 json_encode 函数造成浮点类型数据出现精度问题 Laravel 授权策略(Policy)的基本使用 Ubuntu 系统下 WiFi 频繁掉线解决方法 Laravel 应用部署到 Nginx 服务器上的第一个坑 Ubuntu 16.04 LST 安装 Redis 和 Composer PHP 采集逐浪小说章节列表 Nginx 环境 SSL 强制 HTTP 301 跳转到 HTTPS 【工作&生活】第一周 ServiceStack.Redis 与多线程 Count the number of Duplicates C# Base64 加密及解密 ASP.NET MVC 使用动态类型传递数据 Django 使用 order_by() 对数据进行排序操作 ASP.NET 从客户端中检测到有潜在危险的 Request.Form 值 ASP.NET 使用 FormData 实现 AJAX 上传图片 Python 使用 BeautifulSoup 抓取网页 贪心算法之字符串的完美度 一言不和就造轮子之 CookieHelper ASP.NET 上传图片 DBHelper 类 C# 捕获屏幕源码 用 JavaScript 做一些有趣的事情 第一篇文章 好久不见。 如何防止非法调用 PHP 文件 清明小记。 PHP 生成随机字符串 Z-Blog PHP 程序做 301 跳转 PHP 处理数组常用的几个函数 Sublime Text 3 快捷键总结 PHP 使用 file_get_contents() 函数实现采集网页 使用 C# 编写学生信息管理系统 终于到了。 zblog报错: magic_quotes_gpc 和 safe_mode 世事无常。 如何使用 PHP 上传文件 安卓手机编写和运行 PHP 程序的软件 使用 AJAX 刷新、验证 PHP 图片验证码 PHP 生成图片验证码 PHP 之 session 的使用方法 PHP 之 cookie 的使用方法 PHP 实现分页原理详解 Thinkphp 框架中系统常量在 Js 文件中不解析的解决方法
ASP.NET + jQuery + AJAX 实现用户登录
她和她的猫 · 2017-02-09 · via 文章列表 - 她和她的猫

用户登录在网站中是不可或缺的功能,常见的方法就是使用Form表单将数据提交给后台,后台对帐号密码进行验证从而实现了用户登录。

随着技术的发展,一些网站开始使用 AJAX 的方式进行登录,登录成功后只会刷新局部,从而提升了用户体验。在本文中,将使用ASP.NET和jQuery来实现登录功能。

准备数据库

我们使用SQLServer数据库,创建一章 Users 表,SQL 语句如下:

GO
/****** Object:  Table [dbo].[Users]    Script Date: 2017/2/9 21:25:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users](
	[UserID] [int] IDENTITY(1,1) NOT NULL,
	[UserName] [nvarchar](50) NOT NULL,
	[Password] [nvarchar](50) NOT NULL,
	[RegTime] [datetime] NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
	[UserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

然后往Users表里面插入一条数据:

GO
SET IDENTITY_INSERT [dbo].[Users] ON 
INSERT [dbo].[Users] ([UserID], [UserName], [Password], [RegTime]) VALUES (1, N'her-cat', N'E10ADC3949BA59ABBE56E057F20F883E', CAST(0x0000A715015BDD20 AS DateTime))
SET IDENTITY_INSERT [dbo].[Users] OFF

前端页面

记得在 head 中引入 jQuery 类库。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UserAjaxLoginDemo.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>ASP.NET+jQuery+ AJAX 实现用户登录实例</title>
    <script src="Js/jquery.min.js"></script>
    <style type="text/css">
        #loginForm {
            border: 1px solid gray;
            text-align: center;
            width: 300px;
        }

            #loginForm tr {
                height: 35px;
            }

                #loginForm tr:nth-child(1) {
                    background-color: skyblue;
                    font-weight: bold;
                }
    </style>
</head>
<body>
    <table id="loginForm">
        <tr>
            <td>用户登录</td>
        </tr>
        <tr>
            <td>
                <label>用户名:</label><input type="text" name="userName" value=" " />
            </td>
        </tr>
        <tr>
            <td>
                <label>&nbsp;码:</label><input type="password" name="password" value="" />
            </td>
        </tr>
        <tr>
            <td>
                <input type="button" name="btnSubmit" value="登 录" />
            </td>
        </tr>
    </table>
</body>
</html>

用户在点击登录按钮以后,先验证用户名密码是否为空,然后向 UserLogin.ashx 文件发送 AJAX 请求,如果验证成功,则会在登录按钮下显示登录成功,否则提示相应的错误信息。

<script type="text/javascript">
        $(function () {
            $("input[name='btnSubmit']").click(function () {
                var _this = $(this);
                var userName = $("input[name='userName']").val().trim();
                var password = $("input[name='password']").val().trim();
                if (userName == "") {
                    alert("用户名不能为空!");
                    $("input[name='userName']").focus();
                    return false;
                }
                if (password == "") {
                    alert("密码不能为空!");
                    $("input[name='password']").focus();
                    return false;
                }
                $.ajax({
                    type: "POST",
                    url: "UserLogin.ashx",
                    dataType: "JSON",
                    data: { "userName": userName, "password": password },
                    beforeSend: function () {
                        _this.val("登录中...");
                    },
                    success: function (result) {
                        if (result.statusCode == 200) {
                            var trObj = "<tr><td><span style='color:green;'>登录成功!</span>欢迎您:" + result.username + "</td></tr>";
                            $(trObj).appendTo("#loginForm");
                        } else {
                            alert(result.message);
                        }
                    }
                });
                _this.val("登 录");
            });
        });
</script>

UserLogin.ashx 文件

先判断请求方法是不是POST,然后接收传过来的用户名和密码,并使用 DBHelper 类与数据库中的用户名和密码进行比对,如果比对成功,则使用FormsAuthenticationTicket 创建身份验证票据,并返回用户名和状态码,否则返回对应的错误信息。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using System.Security.Cryptography;
using System.Web.Security;
using System.Text;

namespace UserAjaxLoginDemo
{
    /// <summary>
    /// UserLogin 的摘要说明
    /// </summary>
    public class UserLogin : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            if (context.Request.HttpMethod.ToUpper().Equals("POST"))
            {
                string userName = context.Server.HtmlEncode(context.Request.Form["userName"]);
                string password = context.Server.HtmlEncode(context.Request.Form["password"]);
                if (userName.Trim().Equals(""))
                {
                    this.ResponseJsonMsg(201, "用户名不能为空!");
                }
                if (password.Trim().Equals(""))
                {
                    this.ResponseJsonMsg(201, "密码不能为空!");
                }
                password = this.Str2Md5(password);
                string sql = string.Format("SELECT * FROM Users WHERE UserName = '{0}'", userName);
                DataTable dt = DBHelper.GetInstance().GetDataTable(sql);
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["Password"].ToString().Equals(password))
                    {
                        //创建身份验证票据
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                                       userName,
                                                       DateTime.Now,
                                                       DateTime.Now.AddDays(30),
                                                       true,
                                                       "User",
                                                       FormsAuthentication.FormsCookiePath);
                        //加密身份验证票据 
                        string hash = FormsAuthentication.Encrypt(ticket);
                        //创建要发送到客户端的cookie 
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
                        cookie.Expires = ticket.Expiration;
                        context.Response.SetCookie(cookie);
                        var obj = new
                        {
                            statusCode = 200,
                            username = userName,
                            message = "登录成功!"
                        };
                        context.Response.Write(new JavaScriptSerializer().Serialize(obj));
                    }
                    else
                    {
                        this.ResponseJsonMsg(202, "密码错误!");
                    }
                }
                else
                {
                    this.ResponseJsonMsg(202, "用户不存在!");
                }
            }
        }

        /// <summary>
        /// 响应json消息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="msg"></param>
        public void ResponseJsonMsg(int code, string msg)
        {
            var obj = new
            {
                statusCode = code,
                message = msg
            };
            HttpContext.Current.Response.Write(new JavaScriptSerializer().Serialize(obj));
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 字符串MD5加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string Str2Md5(string str)
        {
            byte[] result = Encoding.Default.GetBytes(str.Trim());
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

总结

总的来说,登录的流程为 AJAX 提交数据 =》后台验证数据并返回相应的消息 =》根据返回的消息进行操作

这是一篇过去很久的文章,其中的信息可能已经有所发展或是发生改变。