<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Log1n.aspx.cs" Inherits="MaYi.Web.Log1n" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <title>蚂蚁OA流程系统</title> <script type="text/javascript" src="login/jquery.min.js?v=<%=MaYi.Common.Constant.JsVersion%>"></script> <style> * { font-family: "微软雅黑","宋体","Arial"; color: #333; margin: 0px; padding: 0px; font-size: 14px; } body.bg { background: #f9f9f9; width: 100%; height: 100%; } .login { width: 430px; height: 380px; position: absolute; left: 50%; margin: 0 0 0 -192px; top: 20%; padding: 0 0px 6px; box-shadow: 0 1px 5px rgba(0, 0, 0, 0.6); } .login .login-btn { border-radius: 4px; margin-left: 50px; } .header span { color: #fff; font-family: "Microsoft YaHei"; font-size: 18px; margin-left: 8px; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.3); } .login label { display: block; height: 42px; color: rgba(0, 0, 0, 0.6); font-family: "Microsoft YaHei"; line-height: 60px; font-size: 16px; margin-left: 50px; font-weight: bolder; margin-top: 0px; } .login input.text { width: 265px; height: 33px; background: none; border: none; line-height: 35px; padding-left: 10px; color: #333; } .login input.border { margin-bottom: 15px; /*border-color: #ff9900 #ff9900 #ff9900 -moz-use-text-color;*/ border-width: 1px 1px 1px 0; border-color: #acc6e9 #acc6e9 #acc6e9 rgba(35, 106, 147, 0.84); border-style: solid solid solid none; } .login p { margin: 20px 0; color: #ccc; } .login p a.wjmm { float: right; color: #ff9900; text-decoration: underline; } .login a.btn { display: block; background: #78aaed; width: 100px; font-size: 18px; height: 45px; line-height: 45px; font-weight: normal; border-radius: 4px; text-align: center; color: #fff; } .login a.btn:hover { background: #2a7fef; } a { text-decoration: none; } a:hover { color: #3e1e1e; text-decoration: none; } img { border: none; } .blue { color: #006699; } .login .err-info { color: red; } table td { position: relative; } .header { background: #78aaed none repeat scroll 0 0; border-bottom: 1px solid #5c8fd3; height: 45px; padding-top: 5px; width: 100%; } .header h3 img { height: 30px; } .logo-img { margin-right: 3px; } .text-center { text-align: center; } .dl_yh_bg { background-color: #78aaed; /*background-color: #969696;*/ display: inline-block; height: 35px; text-align: center; vertical-align: middle; width: 39px; } .dl_yh_pic { margin-top: 10px; } </style> <script type="text/javascript"> (function ($) { $.getUrlParam = function (name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } })(jQuery); $(document).keydown(function (event) { if (event.keyCode == 13) { //绑定回车 login(); } }); $(function () { imgchange(); $("#imgcode").click(function () { imgchange(); }); $('#yzm').val(''); function imgchange() { var radom = "login/LoginHandler.ashx?type=validateCode&rr=" + Math.random(); $("#imgcode").attr("src", radom); } }); var f = true; function login() { // $('#err-info').hide(); if ($('#UserName').val() == "") { $('#UserName').focus(); $('#err-info').html('请输入用户名!'); return false; } else if ($('#pwd').val() == "") { $('#err-info').html('请输入密码!') $('#pwd').focus(); return false; } else if ($('#yzm').val() == "") { $('#err-info').html('请输入验证码!') $('#yzm').focus(); return false; } else { if (f) { f = false; $('#err-info').html('登录中,请稍等......'); $.ajax({ url: "login/LoginHandler.ashx?type=login", cache: false, async: false, type: "POST", data: { name: $('#UserName').val(), pwd: $('#pwd').val(), yzm: $('#yzm').val(), isChecked: $('#isRememb').is(':checked') }, dataType: 'json', success: function (data) { // jQuery.parseJSON(data) if (data.success) { var refUrl = $.getUrlParam("ref"); if (refUrl) window.location = refUrl; else window.location = data.url; } else { $('#err-info').html(data.msg); $("#imgcode").click(); if (data.msg.indexOf("验证码错误") != -1) { $("#yzm").focus(); $("#yzm").select(); } } f = true; }, error: function (e) { f = true; $("#imgcode").click(); $('#err-info').html(jQuery.parseJSON(e.responseText).msg); } }); } } return false; } function valid(o) { if (o == 1) { if ($('#UserName').val() != "") { $('#err-info').html(''); return false; } } else { if ($('#pwd').val() != "") { $('#err-info').html(''); return false; } } } </script> </head> <body class="bg"> <form> <div class="login"> <div class="header"> <h3 class="text-center"> <img class="logo-img" alt="logo" src="login/image/tujia_logo_white.png" /> <span>蚂蚁OA流程系统</span> </h3> </div> <label>登录页</label> <div style="height: 25px"><span class="err-info" id="err-info" style="display: inline; margin-left: 50px"></span></div> <div class="login-btn"> <div style="position: relative;"> <div style="float: left"> <a class="dl_yh_bg" style="cursor: default;"> <img class="dl_yh_pic" src="login/image/dl_yh.png"> </a> </div> <div> <input type="text" class="text border" onblur="valid(1)" id="UserName" name="UserName" placeholder="请输入用户名" /> </div> </div> <div style="position: relative;"> <div style="float: left"> <a class="dl_yh_bg" style="cursor: default;"> <img class="dl_yh_pic" src="login/image/dl_mm.png"> </a> </div> <input type="password" id="pwd" class="text border" onblur="valid(2)" name="Password" placeholder="请输入密码" onkeydown="if(event.keyCode==13)$('#btnConfirm').click();" /> </div> <div style="position: relative;"> <div style="float: left"> <a class="dl_yh_bg" style="cursor: default;"> <img class="dl_yh_pic" src="login/image/yzm.png" width="13" height="17"/> </a> </div> <input type="text" class="text border" style="width: 90px; background: none; padding-left: 10px; color: #333;" name="yzm" id="yzm" placeholder="请输入验证码" /> <img id="imgcode" style="vertical-align: middle; padding-bottom: 5px" title="看不清,换一张" alt="看不清,换一张" /> </div> <div style="position: relative;"><input type="checkbox" style="vertical-align:middle " id="isRememb"/><label for="isRememb" style="display: inline;font-size: 14px;margin-left: 5px;font-weight: normal;line-height: 20px;"><span style="color:gray; vertical-align:middle">两周内自动登录</span></label></div> </div> <div style="margin-left: 270px"><a href="javascript:void(0);" class="btn" onclick="login();" id="btnConfirm">登录</a></div> </div> </form> </body> </html>
后台
using HY.Common.Configuration; using HY.Common.Utility.Utils; using System; using System.Collections.Generic; using System.Data; using System.DirectoryServices; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.SessionState; using MaYi.Common.Business.Service; namespace MaYi.Web.login { /// <summary> /// LoginHandler 的摘要说明 /// </summary> public class LoginHandler : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Cache.SetNoStore(); context.Response.CacheControl = "no-cache"; switch (context.Request["type"]) { case "validateCode": ValidateNumber validate = new ValidateNumber(); string validateCode = validate.CreateValidateNumber(5); context.Session["image"] = validateCode; validate.CreateValidateGraphic(context, validateCode); break; case "login": login(context); break; case "outlogin": //context.Session["UserInfo"] = null; //context.Response.Write(""); break; case "getCookie": // check_cookie(context); break; default: if (HttpContext.Current.Session["UserInfo"] == null) { context.Response.Write("null"); } else { } context.Session["image"] = null; break; } context.Response.End(); } public void login(HttpContext context) { try { Logger.Log.Debug("-----记录登录的ip =" +StringUtils.GetIPAddress()); // 发来请求的客户端IP string name = context.Request["name"]; string pwd = context.Request["pwd"]; string yzm = context.Request["yzm"]; string isChecked = context.Request["isChecked"]; int quickLoginDay = 0; if (!string.IsNullOrEmpty(isChecked) && isChecked == "true") { quickLoginDay = 14; } if (context.Session["image"] != null) { if (string.IsNullOrEmpty(yzm) || context.Session["image"].ToString().ToLower() != yzm.ToLower()) { // context.Response.Write("验证码错误!"); context.Session["image"] = null; context.Response.Write("{\"success\":false,\"msg\":\"验证码错误!\"}"); } else { TJEmployeeExService empExComps = new TJEmployeeExService(); var emp_statues = empExComps.CheckEmployeePassword(name, pwd); var accountStatus = false; if (!emp_statues) accountStatus = ValidateUserAccountAD(ConfigurationManager.AppSettings["domainName"], name, pwd); Logger.Log.Debug("-----AD登陆验证是否成功 accountStatus=" + accountStatus); Logger.Log.Debug("-----系统登陆验证是否成功 emp_statues=" + emp_statues); if (emp_statues || accountStatus) { string url = ConfigurationManager.AppSettings["DefaultLoginedUrl"]; context.Session.Clear(); context.Session["LoginUserName"] = name; context.Session["Lock_LoginUserName"] = name; if(ConfigurationManager.AppSettings["IsStartCas"] != "true") { var cookieU = new HttpCookie("ql_data_u", name); var cookieP = new HttpCookie("ql_data_p", ""); if (quickLoginDay > 0) { cookieP.Value = empExComps.GetEncryptUserPwd(name); cookieU.Expires = DateTime.Now.AddDays(quickLoginDay); cookieP.Expires = DateTime.Now.AddDays(quickLoginDay); } else { cookieU.Expires = DateTime.Now.AddYears(-1); cookieP.Expires = DateTime.Now.AddYears(-1); } context.Response.SetCookie(cookieU); context.Response.SetCookie(cookieP); } //context.Response.Write(url); context.Response.Write("{\"success\":true,\"url\":\"" + url + "\"}"); } else { context.Session["image"] = null; context.Response.Write("{\"success\":false,\"msg\":\"用户名或密码错误!\"}"); } } } else { Logger.Log.Debug("-----验证码还未生成!"); } } catch(Exception ex) { context.Session["image"] = null; Logger.Log.Debug("-----登录失败=" + ex.InnerException.Message); context.Response.Write("{\"success\":false,\"msg\":\"登录失败!\"}"); } } #region ValidateUserAccountAD ad认证 public bool ValidateUserAccountAD(string domainName, string username, string Password) { bool flag = false; try { DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domainName.Trim()), username.Trim(), Password.Trim()); entry.RefreshCache(); flag = true; } catch (Exception e) { flag = false; //throw new Exception(e.Message.ToString()); } return flag; } #endregion public bool IsReusable { get { return false; } } } }
生成验证码
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Web; public class ValidateNumber { //产生验证码的字符集 (易混淆的字符去掉) private string charcode = "1,2,3,4,5,6,8,9,0,a,b,c,d,e,f,g,h,j,k,m,n,p,r,s,u,w,x,y"; /// <summary> /// 验证码的最大长度 /// </summary> public int MaxLength { get { return 10; } } /// <summary> /// 验证码的最小长度 /// </summary> public int MinLength { get { return 1; } } /// <summary> /// 生成验证码 /// </summary> /// <param name="length">指定验证码的长度</param> /// <returns></returns> public string CreateValidateNumber(int length) { string[] CharArray = charcode.Split(',');//将字符串转换为字符数组 string randomCode = ""; int temp = -1; Random rand = new Random(); for (int i = 0; i < length; i++) { if (temp != -1) { rand = new Random(temp * i * ((int)DateTime.Now.Ticks)); } int t = rand.Next(CharArray.Length - 1); while (temp == t) { t = rand.Next(CharArray.Length - 1); } temp = t; randomCode += CharArray[t]; } return randomCode; } /// <summary> /// 创建验证码的图片 /// </summary> /// <param name="context">context对象</param> /// <param name="validateNum">验证码</param> public void CreateValidateGraphic(HttpContext context, string validateNum) { int iwidth = (int)(validateNum.Length * 15); Bitmap image = new Bitmap(iwidth,34); Graphics g = Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(Color.White); Pen blackPen = new Pen(Color.LightGray,1); //画图片的干扰线 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); g.DrawRectangle(blackPen, x1, y1, 1, 1); } Font font = new Font("Arial", 16, (FontStyle.Bold | FontStyle.Italic)); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); int randAngle = 40; //随机转动角度 //画图片的边框线 g.DrawRectangle(new Pen(Color.FromArgb(172, 198, 233)), 0, 0, image.Width - 1, image.Height - 1); //画图片的前景干扰点 for (int i = 0; i < 250; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } //验证码旋转,防止机器识别 char[] chars = validateNum.ToCharArray();//拆散字符串成单字符数组 //文字距中 StringFormat format = new StringFormat(StringFormatFlags.NoClip); format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; GraphicsPath gPath1 = new GraphicsPath(); for (int i = 0; i < chars.Length; i++) { Point dot = new Point(13,14); //graph.DrawString(dot.X.ToString(),fontstyle,new SolidBrush(Color.Black),10,150);//测试X坐标显示间距的 float angle = random.Next(-randAngle, randAngle);//转动的度数 g.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置 g.RotateTransform(angle); // g.DrawString(chars[i].ToString(), f, b, 1, 1, format); g.DrawString(chars[i].ToString(), font, brush, 1, 1, format); //graph.DrawString(chars[i].ToString(),fontstyle,new SolidBrush(Color.Blue),1,1,format); g.RotateTransform(-angle);//转回去 g.TranslateTransform(0, -dot.Y);//移动光标到指定位置,每个字符紧凑显示,避免被软件识别 //Point[] point = { // new Point(random.Next(1, image.Width), random.Next(1, image.Height)), // new Point(random.Next((image.Width / 10) * 2, image.Width), random.Next(1, image.Height)), // new Point(random.Next((image.Width / 10) * 4, image.Width), random.Next(1, image.Height)), // new Point(random.Next(1, image.Width), random.Next(1, image.Height)) // }; //gPath1.AddBeziers(point); //g.DrawPath(new Pen(Color.FromArgb(245,215,163)), gPath1); } // g.DrawString(validateNum, font, brush, 3, 3); //保存图片数据 MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); //输出图片 context.Response.Clear(); context.Response.ContentType = "image/jpeg"; context.Response.BinaryWrite(stream.ToArray()); } finally { g.Dispose(); image.Dispose(); } } /// <summary> /// 得到验证码图片的长度 /// </summary> /// <param name="validateNumLength">验证码的长度</param> /// <returns></returns> public static int GetImageWidth(int validateNumLength) { return (int)(validateNumLength * 14); } /// <summary> /// 得到验证码图片的高度 /// </summary> /// <returns></returns> public static double GetImageHeight() { return 29; } }