码迷,mamicode.com
首页 > 其他好文 > 详细

系统登录详解

时间:2018-07-12 14:34:58      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:oat   images   col   random   用户   oct   username   rms   color   

登录整体思路是:生成的验证码存入session中,然后与提交表单中中输入的验证码作比较。

登陆成功:存入浏览器的cookie中。

注销:清楚浏览器中存入的登录名。

1.验证码页面html

    @using (Html.BeginForm("Login", "Account", FormMethod.Post))
    {
        <div class="login_position">
            <p class="center_text p1 top30_M">xx平台管理</p>
            <div class="hr1"></div>
            <div class="left50_M">
                <div class="login_input top15_M">
                    <img src="~/Content/images/login_person.png" /><input type="text" name="username" autocomplete="off" id="username" placeholder="请输入用户名" />
                </div>
                <div class="login_input top30_M">
                    <img src="~/Content/images/login_lock.png" /><input type="password" name="password" placeholder="请输入密码"/>
                </div>
                <div class="top30_M">
                <input placeholder="验证码" name="code" autocomplete="off" id="code" class="login_input2" style="width:100px;" />
                    <img class="left15_M" onclick="this.src = this.src + ‘?‘ + Math.random();" src="@Url.Action("code","Account")" title="看不清楚,换一张" width="83" height="29" align="absmiddle" style="cursor: pointer;" id="imgcodeaa" />
                </div>
                <input type="submit" value="登     录" class="login_btn top30_M" />
            </div>
        </div>
    }

 

2.控制器

验证码生成代码

        //验证码入口
        [AllowAnonymous]
        public ActionResult Code()
        {
            return File(AccountController.CreateCheckIamge(), @"iamge/Jpeg");
        }

        //验证码生成并且存入服务器session
        private static string GenerateCheckCode()
        {
            try
            {
                int number;
                char code;
                string checkCode = String.Empty;

                System.Random random = new Random();

                for (int i = 0; i < 4; i++)
                {
                    number = random.Next();

                    if (number % 2 == 0)
                        code = (char)(0 + (char)(number % 10));
                    else
                        code = (char)(A + (char)(number % 26));

                    checkCode += code.ToString();
                }

                //Session["CheckCode"] = checkCode;
                System.Web.HttpContext.Current.Session.Add("CheckCode", checkCode.ToLower());
                //Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));       

                return checkCode;
            }
            catch (Exception ex)
            {

                return "";
            }
        }

        //添加水印
        private static byte[] CreateCheckCodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return null;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
            Graphics g = Graphics.FromImage(image);

            try
            {
                //生成随机生成器
                Random random = new Random();

                //清空图片背景色
                g.Clear(Color.White);

                //画图片的背景噪音线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

                Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);

                //画图片的前景噪音点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                //Response.ClearContent();
                //Response.ContentType = "image/Gif";
                //Response.BinaryWrite(ms.ToArray());
                return ms.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }

        public static byte[] CreateCheckIamge()
        {
            return CreateCheckCodeImage(GenerateCheckCode());
        }

登录代码:

[HttpPost]
        [AllowAnonymous]
        public ActionResult Login(FormCollection fc)
        {
            return base.Visit(() =>
            {
                string username = fc["username"];
                string password = fc["password"];
                if (!string.IsNullOrEmpty(username))
                {
                    //获取表单数据
                    if (Session["CheckCode"] == null)
                    {
                        throw new Exception("获取验证码时失败,请确认您是否关闭浏览器 cookie 功能");
                    }
                    string code = Request["code"].ToLower().Trim();
                    string checkcode = Session["CheckCode"].ToString().ToLower().Trim();
                    if (code != checkcode)
                    {
                        return Content("<script>alert(‘验证码输入错误!请重新输入验证码!‘);window.location.href=‘/Account/Login‘</script>");
                    }

                    var model = BLL.Sys.AccountBLL.Instance.GetModel(username, password);
                    if (model == null)
                    {
                        return Content("<script>alert(‘用户名或密码错误!‘);window.location.href=‘/Account/Login‘</script>");
                    }
                    else
                    {
                        //提供对票证的属性和值的访问,这些票证用于 Forms 身份验证对用户进行标识,绑定用户名
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(username, false, (int)FormsAuthentication.Timeout.TotalMinutes);
                        //加密HTTP Cookie 中的 Forms 身份验证票证
                        string enticket = FormsAuthentication.Encrypt(ticket);
                        // 创建和命名新的 Cookie,并为其赋值。
                        HttpCookie cookieofau = new HttpCookie(FormsAuthentication.FormsCookieName, enticket);
                        //HTTP Cookie 添加到 HTTP 响应 Cookie 集合
                        Response.AppendCookie(cookieofau);
                        return RedirectToAction("index", "Home");
                    }
                }
                return View();
            });
        }

用户注销代码:

public ActionResult LogOut()
        {
            return base.Visit(() =>
            {
                //查看是否为已经验证的客户
                if (User.Identity.IsAuthenticated)
                {
                    //获取客户端发送的 Cookie 的集合, Forms 身份验证票证的 Cookie 名称。默认值是“.ASPXAUTH”。
                    HttpCookie authcookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                    //获取 FormsAuthenticationTicket对象 (传值为加密的 票据表示)
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authcookie.Value);
                    //从浏览器删除 Forms 身份验证票证。
                    FormsAuthentication.SignOut();
                }
                return Redirect("/Account/Login");
            });
        }

效果图:

 一个完整的验证码实例:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="jquery-3.3.1.js"></script>
    <style>
        body{
    background: #999;
}
#divID {
        position: fixed;
        left: 47%;
        top: 53%;
        width: 500px;
        margin-left: -200px;
        margin-top: -150px;
        font-family: "黑体";
        /*禁止复制粘贴*/
        -moz-user-select: none;
        -webkit-user-select: none;
        user-select:none;
        color:#fff;
    }
    .register_dialog_info {
        float: left;
        margin-left:10px;
        color: #fff;
        margin-top: 5px;
        font-size: 20px;
    }
    form{padding: 20px 0px;}
    ul li {list-style: none;}
    .sub {
        text-align: center;
    }
    .sub input {
        display: inline-block;
        width: 300px;
        background-color: #999;
        color: rgb(255, 255, 255);
        font-size: 20px;
        text-align: center;
        height: 40px;
        line-height: 40px;
        font-family: 黑体;
        outline: none;
        border: none;
        margin: auto;
        border-radius: 10px;
    }
    input[type = "submit"]:hover{cursor: pointer;}

    .reg-box { padding-left: 30px; }

    .reg-box li { line-height: 44px; width: 500px; overflow: hidden; }

    .reg-box li label { width: 68px; height: 50px; float: left; line-height: 50px; text-align: right; padding-right: 20px; }

    .reg-box li input,.reg-box li select{ border-radius: 3px; padding: 6px 0; font-size: 16px; width: 296px; height: 49px; line-height: 28px; border: 1px solid #dddddd; text-indent: 0.5em; float: left; }

    .reg-box li select option{font-size:16px;}

    /*验证码*/
    .add { width: 128px; height: 44px; float: left; _display: inline; cursor: pointer; margin-left: 20px; }

    .reg-box li .sradd { width: 148px; text-indent: 4px; font-size: 14px; }

    .reg-box li .input-code { width: 106px; padding: 10px; font-family: Arial; font-style: italic; color: red; letter-spacing: 1px; cursor: pointer; text-align: center; text-indent: 0; }

    .yzm,.phoKey { background: #012246; text-align: center; line-height: 44px; color: #fff; border-radius: 3px;}

    .phoKey{letter-spacing: 3px; font-size:18px;}

    .yzmc { background: #dddddd; text-align: center; line-height: 44px; color: #999; }

    .error { clear:both;display:block;color: red; padding-left: 90px; padding-bottom:5px;height:20px;float: left; font-size:12px;line-height: 20px;}

    input { background-color: #fff; outline: none; }

    .reg-box li { width: auto; }

    .reg-box li input.errorC, .errorC{ border: 1px solid blue; }

    .reg-box li input.checkedN , .checkedN{ border: 1px solid #1ece6d; }
    </style>
    <script>
        //文本框默认提示文字
        function textFocus(el) {
            if (el.defaultValue == el.value) { el.value = ‘‘; el.style.color = #333; }
        }
        function textBlur(el) {
            if (el.value == ‘‘) { el.value = el.defaultValue; el.style.color = #999; }
        }

        $(function () {
            /*生成验证码*/
            create_code();

            //登录页面的提示文字
            //账户输入框失去焦点
            (function login_validate() {
                $(".reg-box .account").blur(function () {
                    //reg=/^1[3|4|5|8][0-9]\d{4,8}$/i;//验证手机正则(输入前7位至11位)

                    if ($(this).val() == "" || $(this).val() == "请输入您的账号") {
                        $(this).addClass("errorC");
                        $(this).next().html("账号不能为空!");
                        $(this).next().css("display", "block");
                        $(".sub input").prop(disabled, true);
                    }
                        //                else if($(".reg-box .account").val().length<11)
                        //                {
                        //                    $(this).addClass("errorC");
                        //                    $(this).next().html("账号长度有误!");
                        //                    $(this).next().css("display","block");
                        //                }
                        //                else if(!reg.test($(".reg-box .account").val()))
                        //                {
                        //                    $(this).addClass("errorC");
                        //                    $(this).next().html("账号不存在!");
                        //                    $(this).next().css("display","block");
                        //                }
                    else {
                        $(".sub input").prop(disabled, false);
                        $(this).addClass("checkedN");
                        $(this).removeClass("errorC");
                        $(this).next().empty();
                    }
                });
                /*密码输入框失去焦点*/
                $(".reg-box .admin_pwd").blur(function () {
                    //reg=/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,22}$/;

                    if ($(this).val() == "") {
                        $(this).addClass("errorC");
                        $(this).next().html("密码不能为空!");
                        $(this).next().css("display", "block");
                        $(".sub input").prop(disabled, true);
                    }
                        //                else if(!reg.test($(".admin_pwd").val())) {
                        //                    $(this).addClass("errorC");
                        //                    $(this).next().html("密码为6~12位的数字、字母或特殊字符!");
                        //                    $(this).next().css("display","block");
                        //                }
                    else {
                        $(".sub input").prop(disabled, false);
                        $(this).addClass("checkedN");
                        $(this).removeClass("errorC");
                        $(this).next().empty();
                    }
                });

                /*验证码输入框失去焦点*/
                $(".reg-box .photokey").blur(function () {
                    var code1 = $(.reg-box input.photokey).val().toLowerCase();
                    var code2 = $(".reg-box .phoKey").text().toLowerCase();
                    if (code1 != code2) {
                        $(this).addClass("errorC");
                        $(this).next().next().html("验证码输入错误!!!");
                        $(this).next().next().css("display", "block");
                        $(".sub input").prop(disabled, true);
                    }
                    else {
                        $(".sub input").prop(disabled, false);
                        $(this).removeClass("errorC");
                        $(this).next().next().empty();
                        $(this).addClass("checkedN");
                    }
                })
            })();
        });
        function create_code() {
            function shuffle() {
                var arr = [1, r, Q, 4, S, 6, w, u, D, I, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p,
                    q, 2, s, t, 8, v, 7, x, y, z, A, B, C, 9, E, F, G, H, 0, J, K, L, M, N, O, P, 3, R,
                    5, T, U, V, W, X, Y, Z];
                return arr.sort(function () {
                    return (Math.random() - .5);
                });
            };
            shuffle();
            function show_code() {
                var ar1 = ‘‘;
                var code = shuffle();
                for (var i = 0; i < 6; i++) {
                    ar1 += code[i];
                }
                ;
                //var ar=ar1.join(‘‘);
                $(".reg-box .phoKey").text(ar1);
            };
            show_code();
            $(".reg-box .phoKey").click(function () {
                show_code();
            });
        }
    </script>
</head>
<body>
    <div id="divID">
        <div style="background-color:transparent;">
            <form id="ff" method="post">
                <ul class="reg-box">
                    <li>
                        <label for="">账    号</label>
                        <input type="text" name="accName" value="" class="account" maxlength="11" style="color:#999;" onblur="textBlur(this)" onfocus="textFocus(this)" />
                        <span class="error error5"></span>
                    </li>
                    <li>
                        <label for="">密    码</label>
                        <input type="password" name="accPassWord" class="admin_pwd" value="" style="color:#999;" onblur="textBlur(this)" onfocus="textFocus(this)" />
                        <span class="error error6"></span>
                    </li>
                    <li>
                        <label for="">验证码</label>
                        <input type="text" class="sradd photokey" id="key" value="" style="color:#999;ime-mode:disabled;-webkit-ime-mode:inactive;" onblur="textBlur(this)" onfocus=" textFocus(this) " />
                        <span class="add phoKey"></span>
                        <span class="error error7"></span>
                    </li>
                </ul>
                <div class="sub">
                    <input type="submit" value="立即登录" />
                </div>
            </form>
        </div>
    </div>
</body>
</html>

 

 

 系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解系统登录详解

 

系统登录详解

标签:oat   images   col   random   用户   oct   username   rms   color   

原文地址:https://www.cnblogs.com/zhangtaotqy/p/9299143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!