using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text; using System.Web; using System.Web.Caching; using System.Web.Script.Serialization; namespace Jingyao.AIEmployee { // 仅保留登录成功时供应商返回的员工数据,供同一应用的服务端处理程序使用。 public sealed class Employee { public string PersonId { get; private set; } public string Name { get; private set; } public string AttendanceNumber { get; private set; } public string RoleId { get; private set; } internal Employee(string person, string name, string attendance, string role) { PersonId = person; Name = name; AttendanceNumber = attendance; RoleId = role; } internal Dictionary ToRow() { return new Dictionary { { "人员编号", PersonId }, { "姓名", Name }, { "考勤编号", AttendanceNumber }, { "角色编号", RoleId } }; } } public static class AiEmployeeSessions { const string CookieName = "JY_AI_EMPLOYEE"; const string Prefix = "JY.AI.Employee.v1:"; // 凭据是 32 字节随机数,服务器缓存其摘要。重启、过期、退出后必须重新登录。 static string CacheKey(string ticket) { if (String.IsNullOrEmpty(ticket) || ticket.Length != 43) return null; foreach (char c in ticket) { if (!(c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '_')) return null; } using (SHA256 hash = SHA256.Create()) { return Prefix + Convert.ToBase64String(hash.ComputeHash(Encoding.ASCII.GetBytes(ticket))); } } static string RequestKey(HttpContext context) { HttpCookie cookie = context.Request.Cookies[CookieName]; return cookie == null ? null : CacheKey(cookie.Value); } public static Employee RequireCurrent(HttpContext context) { string key = RequestKey(context); Employee person = key == null ? null : HttpRuntime.Cache.Get(key) as Employee; if (person == null) throw new HttpException(401, "当前员工会话已结束,请重新登录"); return person; } static HttpCookie Cookie(string ticket, bool secure) { return new HttpCookie(CookieName, ticket) { HttpOnly = true, Secure = secure, SameSite = SameSiteMode.Strict, Path = "/submit/" }; } internal static void End(HttpContext context, bool secure) { string key = RequestKey(context); if (key != null) HttpRuntime.Cache.Remove(key); HttpCookie expired = Cookie("", secure); expired.Expires = DateTime.UtcNow.AddDays(-1); context.Response.Cookies.Set(expired); } internal static void Begin(HttpContext context, Employee employee, bool secure) { byte[] bytes = new byte[32]; using (RandomNumberGenerator generator = RandomNumberGenerator.Create()) generator.GetBytes(bytes); string ticket = Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); HttpRuntime.Cache.Insert(CacheKey(ticket), employee, null, DateTime.UtcNow.AddHours(8), Cache.NoSlidingExpiration); context.Response.Cookies.Set(Cookie(ticket, secure)); } } internal sealed class ApiFailure : Exception { internal readonly int Status; internal ApiFailure(int status, string message) : base(message) { Status = status; } } public abstract class EmployeeHandler : IHttpHandler { public bool IsReusable { get { return false; } } protected abstract object Execute(HttpContext context, Dictionary body, bool secure); protected virtual int ResponseLimit(Dictionary body) { return 2097152; } protected virtual int RequestLimit(HttpContext context) { return 4096; } internal static Uri Setting(string name) { Uri uri; if (!Uri.TryCreate(ConfigurationManager.AppSettings[name], UriKind.Absolute, out uri) || !String.IsNullOrEmpty(uri.UserInfo) || !String.IsNullOrEmpty(uri.Query) || !String.IsNullOrEmpty(uri.Fragment) || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) throw new ApiFailure(503, "员工身份服务配置尚未就绪"); return uri; } internal static bool ValidateOrigin(HttpRequest request) { Uri origin = Setting("AiEmployee.PublicOrigin"); if (origin.AbsolutePath != "/" || (origin.Scheme != "https" && !origin.IsLoopback)) throw new ApiFailure(503, "员工身份服务访问地址配置未就绪"); // HTTPS 公网由本机反向代理终止 TLS 时,应用端只接受回环连接。 IPAddress peer; bool loopback = IPAddress.TryParse(request.UserHostAddress, out peer) && IPAddress.IsLoopback(peer); if (!request.IsSecureConnection && !loopback) throw new ApiFailure(403, "请通过本站安全入口访问"); string sentOrigin = request.Headers["Origin"]; Uri source; bool matches; if (!String.IsNullOrEmpty(sentOrigin)) { matches = String.Equals(sentOrigin, origin.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase); } else { matches = Uri.TryCreate(request.Headers["Referer"], UriKind.Absolute, out source) && String.Equals(source.GetLeftPart(UriPartial.Authority), origin.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase); } if (!matches || request.Headers["X-Requested-With"] != "XMLHttpRequest") throw new ApiFailure(403, "请从当前站点访问员工身份服务"); return origin.Scheme == "https"; } internal static string ReadText(Stream stream, int maximum, bool upstream) { using (MemoryStream body = new MemoryStream()) { byte[] chunk = new byte[4096]; int count; while ((count = stream.Read(chunk, 0, chunk.Length)) > 0) { if (body.Length + count > maximum) throw new ApiFailure(upstream ? 502 : 413, upstream ? "登录服务响应超出范围" : "请求内容过大"); body.Write(chunk, 0, count); } return Encoding.UTF8.GetString(body.ToArray()).TrimStart('\uFEFF'); } } internal static object Parse(string text, bool upstream, int maximum = 2097152) { try { return new JavaScriptSerializer { RecursionLimit = 12, MaxJsonLength = maximum }.DeserializeObject(text); } catch (ArgumentException) { throw InvalidJson(upstream); } catch (InvalidOperationException) { throw InvalidJson(upstream); } } static ApiFailure InvalidJson(bool upstream) { return new ApiFailure(upstream ? 502 : 400, upstream ? "登录服务响应格式不符" : "请求数据格式不符"); } public void ProcessRequest(HttpContext context) { HttpResponse response = context.Response; response.ContentType = "application/json"; response.ContentEncoding = Encoding.UTF8; response.Cache.SetCacheability(HttpCacheability.NoCache); response.Cache.SetNoStore(); response.Headers["X-Content-Type-Options"] = "nosniff"; response.SuppressFormsAuthenticationRedirect = true; response.TrySkipIisCustomErrors = true; object result; int responseLimit = 2097152; try { HttpRequest request = context.Request; if (request.HttpMethod != "POST") throw new ApiFailure(405, "请使用 POST 请求"); if (request.QueryString.Count != 0) throw InvalidJson(false); if (!String.Equals((request.ContentType ?? "").Split(';')[0].Trim(), "application/json", StringComparison.OrdinalIgnoreCase)) throw new ApiFailure(415, "请发送 JSON 数据"); bool secure = ValidateOrigin(request); int requestLimit = RequestLimit(context); var body = Parse(ReadText(request.InputStream, requestLimit, false), false, requestLimit) as Dictionary; if (body == null) throw InvalidJson(false); result = Execute(context, body, secure); responseLimit = ResponseLimit(body); } catch (ApiFailure error) { response.StatusCode = error.Status; result = new { message = error.Message }; } catch (HttpException error) { if (error.GetHttpCode() == 401) { response.StatusCode = 401; result = new { message = "当前员工会话已结束,请重新登录" }; } else { response.StatusCode = 503; result = new { message = "员工身份服务暂时不可用" }; } } catch (Exception) { response.StatusCode = 503; result = new { message = "员工身份服务暂时不可用" }; } response.Write(new JavaScriptSerializer { MaxJsonLength = responseLimit }.Serialize(result)); } protected static void NoParameters(Dictionary body) { if (body.Count != 0) throw new ApiFailure(400, "此项操作无需输入参数"); } } public sealed class CurrentHandler : EmployeeHandler { protected override object Execute(HttpContext context, Dictionary body, bool secure) { NoParameters(body); return new { data = AiEmployeeSessions.RequireCurrent(context).ToRow() }; } } public sealed class LogoutHandler : EmployeeHandler { protected override object Execute(HttpContext context, Dictionary body, bool secure) { NoParameters(body); AiEmployeeSessions.End(context, secure); return new { data = true }; } } public sealed class LoginHandler : EmployeeHandler { static string Credential(Dictionary body, string field, int max) { object value; string s = body.TryGetValue(field, out value) ? value as string : null; // 供应商的 type=1 接口用 & 分隔字段。 if (String.IsNullOrWhiteSpace(s) || s.Length > max || s.IndexOf('&') >= 0 || s.IndexOf('=') >= 0 || s.IndexOfAny(new [] { '\r', '\n', '\0' }) >= 0) throw new ApiFailure(400, "账号或密码格式不符合登录接口要求"); return s; } static object Authenticate(string username, string password) { Uri endpoint = Setting("AiEmployee.LoginEndpoint"); if (!endpoint.AbsolutePath.EndsWith("/submit/MESCommonBase.ashx", StringComparison.OrdinalIgnoreCase)) throw new ApiFailure(503, "供应商登录地址配置未就绪"); if (endpoint.Scheme == Uri.UriSchemeHttp && !endpoint.IsLoopback && !(endpoint.Host == "192.168.1.27" && endpoint.Port == 8030)) throw new ApiFailure(503, "登录服务需使用 HTTPS 或已配置的本机通讯服务"); var payload = new { type = "1", name = "菜单系统模块_用户名密码_查询数据_new2", param = "用户名=" + username + "&密码=" + password }; byte[] bytes = Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(payload)); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint); request.Method = "POST"; request.AllowAutoRedirect = false; request.Proxy = null; request.UseDefaultCredentials = false; request.ContentType = "application/json; charset=utf-8"; request.ContentLength = bytes.Length; request.Timeout = 15000; request.ReadWriteTimeout = 15000; try { using (Stream stream = request.GetRequestStream()) stream.Write(bytes, 0, bytes.Length); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) throw new ApiFailure(502, "登录服务暂时不可用"); using (Stream input = response.GetResponseStream()) return Parse(ReadText(input, 65536, true), true); } } catch (WebException error) { if (error.Response != null) error.Response.Close(); throw new ApiFailure(502, "暂时无法连接登录服务"); } } static string Field(Dictionary row, string key, int max) { object value; if (!row.TryGetValue(key, out value) || value == null || !(value is string || value is int || value is long || value is decimal)) throw new ApiFailure(502, "登录服务返回的人员资料不完整"); string text = Convert.ToString(value, CultureInfo.InvariantCulture).Trim(); if (text.Length == 0 || text.Length > max) throw new ApiFailure(502, "登录服务返回的人员资料不完整"); return text; } static string NumericId(Dictionary row, string key) { int value; if (!Int32.TryParse(Field(row, key, 12), NumberStyles.None, CultureInfo.InvariantCulture, out value) || value <= 0) throw new ApiFailure(502, "登录服务返回的人员或角色编号无效"); return value.ToString(CultureInfo.InvariantCulture); } protected override object Execute(HttpContext context, Dictionary body, bool secure) { AiEmployeeSessions.End(context, secure); if (body.Count != 2) throw new ApiFailure(400, "请提交登录账号和密码"); object upstream = Authenticate(Credential(body, "username", 128), Credential(body, "password", 256)); var denial = upstream as Dictionary; object flag; if (denial != null && denial.TryGetValue("result", out flag) && Convert.ToString(flag) == "0") throw new ApiFailure(401, "账号或密码错误"); var records = upstream as object[]; if (records == null || records.Length > 128) throw new ApiFailure(502, "登录服务返回的数据格式不符"); if (records.Length == 0) throw new ApiFailure(401, "账号或密码错误"); var allowed = new List>(); Employee first = null; foreach (object record in records) { var row = record as Dictionary; if (row == null) throw new ApiFailure(502, "登录服务返回的数据格式不符"); if (row.TryGetValue("result", out flag) && Convert.ToString(flag) == "0") throw new ApiFailure(401, "账号或密码错误"); var employee = new Employee(NumericId(row, "人员编号"), Field(row, "姓名", 150), Field(row, "考勤编号", 128), NumericId(row, "角色编号")); if (first == null) first = employee; else if (first.PersonId != employee.PersonId || first.AttendanceNumber != employee.AttendanceNumber || first.Name != employee.Name) throw new ApiFailure(502, "登录结果没有唯一对应到一名员工"); var safe = employee.ToRow(); safe["session_id"] = Field(row, "session_id", 4000); allowed.Add(safe); } AiEmployeeSessions.Begin(context, first, secure); return allowed; } } }