private static string GetContextId(HttpRequestBase request, CapttiaSection config, Encryption encryption) { var contextId = AnonymousIdentifier.GetContextId(request.RequestContext.HttpContext); // Check for existing cookie var existingCookie = request.Cookies[config.CookieName]; if (existingCookie != null) { var cookieId = existingCookie.Value; if (!string.IsNullOrWhiteSpace(cookieId)) { try { var decryptedCookieId = encryption.Decrypt(cookieId, config.PassPhraseB); var cookieBrowserId = AnonymousIdentifier.GetBrowserStampFromId(decryptedCookieId); var contextBrowserId = AnonymousIdentifier.GetBrowserStampFromId(contextId); if (cookieBrowserId.Equals(contextBrowserId)) { contextId = decryptedCookieId; } } catch (CryptographicException) { request.Cookies[config.CookieName].Expires = DateTime.Today.AddDays(-1); } } } return contextId; }
/// <summary> /// Writes a CAPTTIA element to the form. /// </summary> /// <param name="html"></param> /// <param name="request"></param> /// <returns></returns> public static MvcHtmlString Capttia(this HtmlHelper html, HttpRequestBase request) { var config = ConfigurationManager.GetSection("capttia") as CapttiaSection; var encryption = new Encryption(); var ids = new ScriptIds(config.ModuleName); string contextId = GetContextId(request, config, encryption); // Place it in a cookie var cookieContextId = encryption.Encrypt(contextId, config.PassPhraseB); request.RequestContext.HttpContext.Response.SetCookie(new HttpCookie(config.CookieName, cookieContextId) { HttpOnly = true }); // Place it on the form var formId = encryption.Encrypt(contextId, config.PassPhrase); var token = JavaScript.EncodeForSingleQuotes(formId); return MvcHtmlString.Create(GetHoneyPot(ids) + GetScriptElement(ids, token)); }