using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web; using System.Web.Helpers; using Abp.Extensions; using Abp.Web.Security.AntiForgery; using IwbZero.ToolCommon.LogHelpers; namespace IwbZero.AntiForgery { public static class IwbAntiForgeryManagerMvcExtensions { #region MVC public static bool IsValid_Iwb(this IAbpAntiForgeryManager manager, HttpContextBase context) { var antiForgeryCookieValue = GetCookieValue(context, AntiForgeryConfig.CookieName); if (antiForgeryCookieValue.IsNullOrEmpty()) { var authCookieValue = GetCookieValue(context, manager.Configuration.AuthorizationCookieName); return authCookieValue.IsNullOrEmpty(); } var formOrHeaderValue = manager.Configuration.GetFormOrHeaderValue(context); if (formOrHeaderValue.IsNullOrEmpty()) { return false; } return manager.As().IsValid(antiForgeryCookieValue, formOrHeaderValue); } private static string GetCookieValue(HttpContextBase context, string cookieName) { var cookie = context.Request.Cookies[cookieName]; return cookie?.Value; } private static string GetFormOrHeaderValue(this IAbpAntiForgeryConfiguration configuration, HttpContextBase context) { var headerValues = context.Request.Headers.GetValues(configuration.TokenHeaderName); var headersArray = headerValues?.ToArray(); if (headersArray == null || !headersArray.Any()) { var formValue = context.Request.Form["__RequestVerificationToken"]; if (!formValue.IsNullOrEmpty()) { return formValue; } return null; } return headersArray.Last().Split(", ").Last(); } #endregion #region API public static bool IsValid_Iwb(this IAbpAntiForgeryManager manager, HttpRequestHeaders headers) { var antiForgeryCookieValue = GetCookieValue(manager.Configuration.TokenCookieName, headers); if (antiForgeryCookieValue.IsNullOrEmpty()) { var authCookieValue = GetCookieValue(manager.Configuration.AuthorizationCookieName, headers); return authCookieValue.IsNullOrEmpty(); } var headerTokenValue = GetHeaderValue(manager, headers); if (headerTokenValue.IsNullOrEmpty()) { return false; } // var flag= manager.As().IsValid(antiForgeryCookieValue, headerTokenValue); var flag = antiForgeryCookieValue == headerTokenValue; typeof(IwbAntiForgeryManagerMvcExtensions).LogDebug($"Result======>【Api】[{flag}]"); return flag; } private static string GetCookieValue(string cookieName, HttpRequestHeaders headers) { var cookie = headers.GetCookies(cookieName).LastOrDefault(); return cookie?[cookieName].Value; } private static string GetHeaderValue(IAbpAntiForgeryManager manager, HttpRequestHeaders headers) { if (!headers.TryGetValues(manager.Configuration.TokenHeaderName, out var headerValues)) { return null; } var headersArray = headerValues.ToArray(); if (!headersArray.Any()) { return null; } return headersArray.Last().Split(", ").Last(); } #endregion } }