/// <summary> /// Initializes a new instance of the <see cref="HtmlHelper"/> class. /// </summary> public HtmlHelper( [NotNull] ICompositeViewEngine viewEngine, [NotNull] IModelMetadataProvider metadataProvider, [NotNull] IUrlHelper urlHelper, [NotNull] AntiForgery antiForgeryInstance, [NotNull] IActionBindingContextProvider actionBindingContextProvider) { _viewEngine = viewEngine; MetadataProvider = metadataProvider; _urlHelper = urlHelper; _antiForgeryInstance = antiForgeryInstance; _actionBindingContextProvider = actionBindingContextProvider; // Underscores are fine characters in id's. IdAttributeDotReplacement = "_"; }
public object Any(AntiForgeryTest request) { AntiForgery.Validate(); return(request); }
public MvcHtmlString AntiForgeryToken(string salt, string domain, string path) { return(new MvcHtmlString(AntiForgery.GetHtml(ViewContext.HttpContext, salt, domain, path).ToString())); }
public JsonResult SignUp( User model, string FirstName, string Surname, string signupPass1, string signupPass2, string securityQuestion, string mobilePhone, string mobileCode, string isInCaptchaMode, int whiteLabelId ) { string id = Guid.NewGuid().ToString("N"); const int idChunkSize = 4; string uniqueID = string.Join("-", Enumerable.Range(0, id.Length / idChunkSize).Select(i => id.Substring(i * idChunkSize, idChunkSize)) ); log.Debug("Sign up client attempt id: '{0}'...", uniqueID); this.cookiesToRemoveOnSignup.Clear(); if (!ModelState.IsValid) { return(GetModelStateErrors(ModelState)); } if (model.SecurityAnswer.Length > 199) { throw new Exception(DbStrings.MaximumAnswerLengthExceeded); } CustomerOrigin uiOrigin = UiCustomerOrigin.Get(); string alibabaID = GetAndRemoveCookie("alibaba_id"); if (uiOrigin.IsAlibaba() && string.IsNullOrWhiteSpace(alibabaID)) { return(Json(new { success = false, errorMessage = "No Alibaba customer id provided.", }, JsonRequestBehavior.AllowGet)); } // if var blm = new WizardBrokerLeadModel(Session); CampaignSourceRef campaignSourceRef = null; if (!blm.BrokerFillsForCustomer) { campaignSourceRef = new CampaignSourceRef { FContent = GetAndRemoveCookie("fcontent"), FMedium = GetAndRemoveCookie("fmedium"), FName = GetAndRemoveCookie("fname"), FSource = GetAndRemoveCookie("fsource"), FTerm = GetAndRemoveCookie("fterm"), FUrl = GetAndRemoveCookie("furl"), FDate = ToDate(GetAndRemoveCookie("fdate")), RContent = GetAndRemoveCookie("rcontent"), RMedium = GetAndRemoveCookie("rmedium"), RName = GetAndRemoveCookie("rname"), RSource = GetAndRemoveCookie("rsource"), RTerm = GetAndRemoveCookie("rterm"), RUrl = GetAndRemoveCookie("rurl"), RDate = ToDate(GetAndRemoveCookie("rdate")), }; } // if string visitTimes = GetAndRemoveCookie("sourceref_time"); var signupModel = new SignupCustomerMultiOriginModel { UserName = model.EMail, Origin = uiOrigin.GetOrigin(), RawPassword = new DasKennwort(signupPass1), RawPasswordAgain = new DasKennwort(signupPass2), PasswordQuestion = Convert.ToInt32(securityQuestion), PasswordAnswer = model.SecurityAnswer, RemoteIp = RemoteIp(), FirstName = FirstName, LastName = Surname, CaptchaMode = isInCaptchaMode == "True", MobilePhone = mobilePhone, MobileVerificationCode = mobileCode, BrokerFillsForCustomer = blm.BrokerFillsForCustomer, WhiteLabelID = whiteLabelId, IsTest = (Request.Cookies["istest"] != null) ? true : (bool?)null, CampaignSourceRef = campaignSourceRef, GoogleCookie = blm.BrokerFillsForCustomer ? string.Empty : GetAndRemoveCookie("__utmz"), ReferenceSource = blm.BrokerFillsForCustomer ? "Broker" : GetAndRemoveCookie("sourceref"), AlibabaID = blm.BrokerFillsForCustomer ? null : GetAndRemoveCookie("alibaba_id"), ABTesting = GetAndRemoveCookie("ezbobab"), VisitTimes = visitTimes, FirstVisitTime = HttpUtility.UrlDecode(visitTimes), RequestedLoanAmount = GetAndRemoveCookie("loan_amount"), RequestedLoanTerm = GetAndRemoveCookie("loan_period"), BrokerLeadID = blm.LeadID, BrokerLeadEmail = blm.LeadEmail, BrokerLeadFirstName = blm.FirstName, }; log.Debug( "Sign up client attempt id: '{0}', model is {1}.", uniqueID, signupModel.ToLogStr() ); try { log.Debug("Sign up client attempt id: '{0}', requesting backend sign up.", uniqueID); UserLoginActionResult signupResult = this.serviceClient.Instance.SignupCustomerMultiOrigin(signupModel); log.Debug("Sign up client attempt id: '{0}', backend sign up complete.", uniqueID); MembershipCreateStatus status = (MembershipCreateStatus)Enum.Parse( typeof(MembershipCreateStatus), signupResult.Status ); log.Debug("Sign up client attempt id: '{0}', status is {1}.", uniqueID, status); if (status == MembershipCreateStatus.DuplicateEmail) { return(Json( new { success = false, errorMessage = signupResult.ErrorMessage, }, JsonRequestBehavior.AllowGet )); } // if if ((status != MembershipCreateStatus.Success) || !string.IsNullOrWhiteSpace(signupResult.ErrorMessage)) { throw new Exception(string.IsNullOrWhiteSpace(signupResult.ErrorMessage) ? string.Format("Failed to sign up (error code is '{0}').", uniqueID) : signupResult.ErrorMessage ); } // if ObjectFactory.GetInstance <IEzbobWorkplaceContext>().SessionId = signupResult.SessionID.ToString(CultureInfo.InvariantCulture); Session["UserSessionId"] = signupResult.SessionID; this.context.SetSessionOrigin(uiOrigin.GetOrigin()); FormsAuthentication.SetAuthCookie(model.EMail, false); HttpContext.User = new GenericPrincipal(new GenericIdentity(model.EMail), new[] { "Customer" }); RemoveCookiesOnSignup(); log.Debug("Sign up client attempt id: '{0}', sign up complete.", uniqueID); return(Json( new { success = true, antiforgery_token = AntiForgery.GetHtml().ToString(), refNumber = signupResult.RefNumber, }, JsonRequestBehavior.AllowGet )); } catch (Exception e) { log.Alert(e, "Failed to sign up, client attempt id: {0}.", uniqueID); return(Json( new { success = false, errorMessage = string.Format( "Failed to sign up, please call support (error code is '{0}').", uniqueID ), }, JsonRequestBehavior.AllowGet )); } // try } // SignUp
public ActionResult Settings(SettingsViewModel model) { AntiForgery.Validate(); return(View("Index")); }
public ActionResult CreateSiteCollection(CreateSiteCollectionViewModel model) { switch (model.Step) { case CreateSiteStep.SiteInformation: ModelState.Clear(); if (String.IsNullOrEmpty(model.Title)) { // Set initial value for PnP Partner Pack Extensions Enabled model.PartnerPackExtensionsEnabled = true; model.ResponsiveDesignEnabled = true; } break; case CreateSiteStep.TemplateParameters: if (!ModelState.IsValid) { model.Step = CreateSiteStep.SiteInformation; } else { if (!String.IsNullOrEmpty(model.ProvisioningTemplateUrl) && model.ProvisioningTemplateUrl.IndexOf(PnPPartnerPackConstants.PnPProvisioningTemplates) > 0) { String templateSiteUrl = model.ProvisioningTemplateUrl.Substring(0, model.ProvisioningTemplateUrl.IndexOf(PnPPartnerPackConstants.PnPProvisioningTemplates)); String templateFileName = model.ProvisioningTemplateUrl.Substring(model.ProvisioningTemplateUrl.IndexOf(PnPPartnerPackConstants.PnPProvisioningTemplates) + PnPPartnerPackConstants.PnPProvisioningTemplates.Length + 1); String templateFolder = String.Empty; if (templateFileName.IndexOf("/") > 0) { templateFolder = templateFileName.Substring(0, templateFileName.LastIndexOf("/") - 1); templateFileName = templateFileName.Substring(templateFolder.Length + 1); } model.TemplateParameters = PnPPartnerPackUtilities.GetProvisioningTemplateParameters( templateSiteUrl, templateFolder, templateFileName); } } break; case CreateSiteStep.SiteCreated: AntiForgery.Validate(); if (ModelState.IsValid) { // Prepare the Job to provision the Site Collection SiteCollectionProvisioningJob job = new SiteCollectionProvisioningJob(); // Prepare all the other information about the Provisioning Job job.SiteTitle = model.Title; job.Description = model.Description; job.Language = model.Language; job.TimeZone = model.TimeZone; job.RelativeUrl = String.Format("/{0}/{1}", model.ManagedPath, model.RelativeUrl); job.SitePolicy = model.SitePolicy; job.Owner = ClaimsPrincipal.Current.Identity.Name; job.PrimarySiteCollectionAdmin = model.PrimarySiteCollectionAdmin != null && model.PrimarySiteCollectionAdmin.Length > 0 ? model.PrimarySiteCollectionAdmin[0].Email : null; job.SecondarySiteCollectionAdmin = model.SecondarySiteCollectionAdmin != null && model.SecondarySiteCollectionAdmin.Length > 0 ? model.SecondarySiteCollectionAdmin[0].Email : null; job.ProvisioningTemplateUrl = model.ProvisioningTemplateUrl; job.StorageMaximumLevel = model.StorageMaximumLevel; job.StorageWarningLevel = model.StorageWarningLevel; job.UserCodeMaximumLevel = model.UserCodeMaximumLevel; job.UserCodeWarningLevel = model.UserCodeWarningLevel; job.ExternalSharingEnabled = model.ExternalSharingEnabled; job.ResponsiveDesignEnabled = model.ResponsiveDesignEnabled; job.PartnerPackExtensionsEnabled = model.PartnerPackExtensionsEnabled; job.Title = String.Format("Provisioning of Site Collection \"{1}\" with Template \"{0}\" by {2}", job.ProvisioningTemplateUrl, job.RelativeUrl, job.Owner); job.TemplateParameters = model.TemplateParameters; model.JobId = ProvisioningRepositoryFactory.Current.EnqueueProvisioningJob(job); } break; default: break; } return(PartialView(model.Step.ToString(), model)); }
public MvcHtmlString AntiForgeryToken() { return(new MvcHtmlString(AntiForgery.GetHtml().ToString())); }
public ActionResult PlayWithMail(PlayWithMailViewModel model) { if (!ModelState.IsValid) { return(View("Index", model)); } AntiForgery.Validate(); var folders = MailHelper.ListFolders(); // Here you can use whatever mailbox name that you like, instead of Inbox f.Name == "发件箱" || var messages = MailHelper.ListMessages(folders.FirstOrDefault(f => f.Name == "收件箱").Id); if (messages != null && messages.Count > 0) { var message = MailHelper.GetMessage(messages[0].Id, true); foreach (var attachment in message.Attachments) { // Download content only for attachments smaller than 100K if (attachment.Size < 100 * 1024) { attachment.EnsureContent(); } } } MailHelper.SendMessage(new Models.MailMessageToSend { Message = new Models.MailMessage { Subject = "Test message", Body = new Models.ItemBody { Content = "<html><body><h1>Hello from ASP.NET MVC calling Microsoft Graph API!</h1></body></html>", Type = Models.BodyType.Html, }, To = new List <Models.UserInfoContainer>( new Models.UserInfoContainer[] { new Models.UserInfoContainer { Recipient = new Models.UserInfo { Name = model.MailSendToDescription, Address = model.MailSendTo } } }), }, SaveToSentItems = true, }); if (messages != null && messages.Count > 0) { MailHelper.Reply(messages[0].Id, "This a direct reply!"); MailHelper.ReplyAll(messages[0].Id, "This a reply all!"); /* MailHelper.Forward(messages[0].Id, * new List<Models.UserInfoContainer>( * new Models.UserInfoContainer[] * { * new Models.UserInfoContainer * { * Recipient = new Models.UserInfo * { * Name = model.MailSendToDescription, * Address = model.MailSendTo, * } * }, * new Models.UserInfoContainer * { * Recipient = new Models.UserInfo * { * Address = "*****@*****.**", * Name = "Tenant Admin", * } * }, * }), * "Hey! Look at this!"); */ } return(View("Index")); }
public override void Execute() { WriteLiteral("\r\n\r\n"); Page.Title = AdminResources.LoginTitle; // No admin password has been registered so redirect if (!AdminSecurity.HasAdminPassword()) { SiteAdmin.RedirectToRegister(Response); return; } if (IsPost) { AntiForgery.Validate(); var password = Request.Form["password"]; if (AdminSecurity.CheckPassword(password)) { // Get the return url var returnUrl = SiteAdmin.GetReturnUrl(Request) ?? SiteAdmin.AdminVirtualPath; // Set the admin auth cookie AdminSecurity.SetAuthCookie(Response); // Redirect to the return url Response.Redirect(returnUrl); } else { ModelState.AddError("password", AdminResources.Validation_PasswordIncorrect); } } WriteLiteral("\r\n"); DefineSection("Head", () => { WriteLiteral("\r\n <script type=\"text/javascript\">\r\n function showForgotPasswordInfo(){\r\n " + " document.getElementById(\'forgotPasswordInfo\').style.display = \'\';\r\n }\r\n" + " </script>\r\n"); }); WriteLiteral("\r\n\r\n"); Write(Html.ValidationSummary()); WriteLiteral("\r\n<br />\r\n\r\n<form method=\"post\" action=\"\">\r\n "); Write(AntiForgery.GetHtml()); WriteLiteral("\r\n <fieldset>\r\n <ol>\r\n <li class=\"password\">\r\n <label for" + "=\"password\">"); Write(AdminResources.Password); WriteLiteral(":</label>\r\n "); Write(Html.Password("password")); WriteLiteral(" "); Write(Html.ValidationMessage("password", "*")); WriteLiteral("\r\n </ol>\r\n <p class=\"form-actions\">\r\n <input type=\"submit\" value=\""); Write(AdminResources.Login); WriteLiteral("\" />\r\n </p>\r\n </fieldset>\r\n <p>\r\n <a href=\"#\" onclick=\"showForgot" + "PasswordInfo(); return false;\">"); Write(AdminResources.ForgotPassword); WriteLiteral("</a>\r\n </p>\r\n</form>\r\n<br />\r\n"); var passwordFileLocation = AdminSecurity.AdminPasswordFile.TrimStart('~', '/'); var forgotPasswordHelp = String.Format(CultureInfo.CurrentCulture, AdminResources.AdminPasswordChangeInstructions, Html.Encode(passwordFileLocation)); WriteLiteral("<span id=\"forgotPasswordInfo\" style=\"display: none\">"); Write(Html.Raw(forgotPasswordHelp)); WriteLiteral("</span>"); }
public void TearDown() { AntiForgery.ClearInstance(); }
/// <summary> /// Generates an anti-forgery token that can be manually added to an HTTP request header, /// e.g., from within an AJAX request. /// </summary> /// <param name="request">HTTP request message.</param> /// <returns>Anti-forgery token to be added as an HTTP header value.</returns> public static string GenerateRequestVerficationHeaderToken(this HttpRequestMessage request) { AntiForgery.GetTokens(request, null, out string cookieToken, out string formToken); return($"{cookieToken}:{formToken}"); }
public void ProcessRequest(HttpContext context) { AntiForgery.Validate(); if (!WebUser.IsAuthenticated) { throw new HttpException(401, "You must login !"); } if (!WebUser.HasRole(UserRoles.Admin) && !WebUser.HasRole(UserRoles.Editor) && !WebUser.HasRole(UserRoles.Author)) { throw new HttpException(401, "You do not have permission to do this"); } //treba nam mode jer cemo u zavisnosti od njega, ako je edit da ispravljamo post ako je new da pravimo novi... var mode = context.Request.Form["mode"]; var title = context.Request.Form["postTitle"]; var content = context.Request.Form["postContent"]; var slug = context.Request.Form["postSlug"]; var datePublished = context.Request.Form["postDatePublished"]; var id = context.Request.Form["postId"]; var postTags = context.Request.Form["postTags"]; var authorId = context.Request.Form["postAuthorId"]; IEnumerable <int> tags = new int[] { }; if (!string.IsNullOrEmpty(postTags)) { tags = postTags.Split(',').Select(v => Convert.ToInt32(v)); } if ((mode == "edit" || mode == "delete") && WebUser.HasRole(UserRoles.Author)) { if (WebUser.UserId != Convert.ToInt32(authorId)) { throw new HttpException(401, "You do not have permission to do this"); } } if (string.IsNullOrWhiteSpace(slug)) { CreateSlug(title); } if (mode == "edit") { EditPost(Convert.ToInt32(id), title, content, slug, datePublished, Convert.ToInt32(authorId), tags); } else if (mode == "new") { CreatePost(title, content, slug, datePublished, WebUser.UserId, tags); } else if (mode == "delete") { DeletePost(slug); } context.Response.Redirect("~/admin/post/"); }
public void OnAuthorization(AuthorizationContext filterContext) { Requires.NotNull(filterContext, nameof(filterContext)); AntiForgery.Validate(GetAntiForgeryCookieToken(filterContext), GetAntiForgeryHeaderToken(filterContext)); }
/// <summary> /// Maps Form data (for an HTTP POST request) to properies of a given Entity Model and performs basic validation. /// </summary> /// <param name="model">The Entity Model to map the form data to.</param> /// <returns><c>true</c> if there is any form data to be mapped.</returns> protected bool MapRequestFormData(EntityModel model) { if (Request.HttpMethod != "POST") { return(false); } // CSRF protection: If the anti CSRF cookie is present, a matching token must be in the form data too. const string antiCsrfToken = "__RequestVerificationToken"; if (Request.Cookies[antiCsrfToken] != null) { AntiForgery.Validate(); } Type modelType = model.GetType(); foreach (string formField in Request.Form) { if (formField == antiCsrfToken) { // This is not a form field, but the anti CSRF token (already validated above). continue; } PropertyInfo modelProperty = modelType.GetProperty(formField); if (modelProperty == null) { Log.Debug("Model [{0}] has no property for form field '{1}'", model, formField); continue; } string formFieldValue = Request.Form[formField]; ValidationAttribute validationAttr = modelProperty.GetCustomAttribute <ValidationAttribute>(); if (validationAttr != null) { try { validationAttr.Validate(formFieldValue, formField); } catch (ValidationException ex) { string validationMessage = ResolveValidationMessage(ex.Message, model); Log.Debug("Validation of property '{0}' failed: {1}", formField, validationMessage); ModelState.AddModelError(formField, validationMessage); continue; } } try { if (modelProperty.PropertyType == typeof(bool)) { // The @Html.CheckBoxFor method includes a hidden field with the original checkbox state, resulting in two boolean values (comma separated) formFieldValue = formFieldValue.Split(',')[0]; } modelProperty.SetValue(model, Convert.ChangeType(formFieldValue, modelProperty.PropertyType)); } catch (Exception ex) { Log.Debug("Failed to set Model [{0}] property '{1}' to value obtained from form data: '{2}'. {3}", model, formField, formFieldValue, ex.Message); ModelState.AddModelError(formField, ex.Message); } } return(true); }
public void GetHtml_ThrowsWhenNotCalledInWebContext() { Assert.Throws <ArgumentException>(() => AntiForgery.GetHtml(), "An HttpContext is required to perform this operation. Check that this operation is being performed during a web request."); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true); if (skipAuthorization) { return; } var request = filterContext.RequestContext.HttpContext.Request; var response = filterContext.RequestContext.HttpContext.Response; bool isAjaxRequest = request.IsAjaxRequest(); string userAgent = request.UserAgent; string returnUrl = isAjaxRequest == true ? request.UrlReferrer.AbsoluteUri : request.Url.AbsoluteUri; if (request.HttpMethod == "POST") { if (request.IsAjaxRequest()) { var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName]; var cookieValue = antiForgeryCookie != null ? antiForgeryCookie.Value : null; //从cookies 和 Headers 中 验证防伪标记 //这里可以加try-catch AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]); } } string token = request.QueryString["token"]; if (token != null) { HttpCookie cookie_session = request.Cookies[OwnRequest.SESSION_NAME]; if (cookie_session != null) { cookie_session.Value = token; response.AppendCookie(cookie_session); } else { response.Cookies.Add(new HttpCookie(OwnRequest.SESSION_NAME, token)); } } var userInfo = OwnRequest.GetUserInfo(); if (userInfo == null) { MessageBox messageBox = new MessageBox(); messageBox.No = Guid.NewGuid().ToString(); messageBox.Type = MessageBoxTip.Failure; messageBox.Title = "温馨提示"; messageBox.GoToUrl = OwnWebSettingUtils.GetLoginPage(returnUrl); messageBox.Content = "请先<a href=\"javascript:void(0)\" onclick=\"window.top.location.href='" + WebMobile.Areas.Wb.Own.OwnWebSettingUtils.GetLoginPage(returnUrl) + "'\">登录</a>后打开"; messageBox.IsTop = true; if (isAjaxRequest) { CustomJsonResult jsonResult = new CustomJsonResult(ResultType.Exception, ResultCode.Exception, messageBox.Title, messageBox); //jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet; filterContext.Result = jsonResult; filterContext.Result.ExecuteResult(filterContext); filterContext.HttpContext.Response.End(); } else { filterContext.Result = new ViewResult { ViewName = "MessageBox", MasterName = "_Layout", ViewData = new ViewDataDictionary { Model = messageBox } }; } return; } if (_permissions != null) { MessageBox messageBox = new MessageBox(); messageBox.No = Guid.NewGuid().ToString(); messageBox.Type = MessageBoxTip.Warn; messageBox.Title = "温馨提示"; messageBox.Content = "您没有权限"; bool isHasPermission = OwnRequest.IsInPermission(_permissions); if (!isHasPermission) { if (isAjaxRequest) { CustomJsonResult jsonResult = new CustomJsonResult(ResultType.Exception, ResultCode.Exception, messageBox.Title, messageBox); //jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet; filterContext.Result = jsonResult; filterContext.Result.ExecuteResult(filterContext); filterContext.HttpContext.Response.End(); } else { filterContext.Result = new ViewResult { ViewName = "MessageBox", MasterName = "_Layout", ViewData = new ViewDataDictionary { Model = messageBox } }; } return; } } OwnRequest.Postpone(); base.OnActionExecuting(filterContext); }
public ActionResult PlayWithCalendars(PlayWithMailViewModel model) { if (!ModelState.IsValid) { return(View("Index", model)); } AntiForgery.Validate(); var calendars = CalendarHelper.ListCalendars(); var calendar = CalendarHelper.GetCalendar(calendars[0].Id); var events = CalendarHelper.ListEvents(calendar.Id, 0); var eventsCalendarView = CalendarHelper.ListEvents(calendar.Id, DateTime.Now, DateTime.Now.AddDays(10), 0); if (events[0].ResponseStatus != null && events[0].ResponseStatus.Response == Models.ResponseType.NotResponded) { CalendarHelper.SendFeedbackForMeetingRequest( calendar.Id, events[0].Id, MeetingRequestFeedback.Accept, "I'm looking forward to meet you!"); } var singleEvent = CalendarHelper.CreateEvent(calendars[0].Id, new Models.Event { Attendees = new List <Models.UserInfoContainer>( new Models.UserInfoContainer[] { new Models.UserInfoContainer { Recipient = new Models.UserInfo { Name = model.MailSendToDescription, Address = model.MailSendTo, } }, new Models.UserInfoContainer { Recipient = new Models.UserInfo { Address = "*****@*****.**", Name = "Someone Else", } }, }), Start = new Models.TimeInfo { DateTime = DateTime.Now.AddDays(2).ToUniversalTime(), TimeZone = "UTC" }, OriginalStartTimeZone = "UTC", End = new Models.TimeInfo { DateTime = DateTime.Now.AddDays(2).AddHours(1).ToUniversalTime(), TimeZone = "UTC" }, OriginalEndTimeZone = "UTC", Importance = Models.ItemImportance.High, Subject = "Introducing the Microsoft Graph API", Body = new Models.ItemBody { Content = "<html><body><h2>Let's talk about the Microsoft Graph API!</h2></body></html>", Type = Models.BodyType.Html, }, Location = new Models.EventLocation { Name = "PiaSys.com Head Quarters", }, IsAllDay = false, IsOrganizer = true, ShowAs = Models.EventStatus.WorkingElsewhere, Type = Models.EventType.SingleInstance, }); var nextMonday = DateTime.Now.AddDays(((int)DayOfWeek.Monday - (int)DateTime.Now.DayOfWeek + 7) % 7); var nextMonday9AM = new DateTime(nextMonday.Year, nextMonday.Month, nextMonday.Day, 9, 0, 0); var lastDayOfMonth = new DateTime(nextMonday.AddMonths(1).Year, nextMonday.AddMonths(1).Month, 1).AddDays(-1); var eventSeries = CalendarHelper.CreateEvent(calendars[0].Id, new Models.Event { Start = new Models.TimeInfo { DateTime = nextMonday9AM.ToUniversalTime(), TimeZone = "UTC" }, OriginalStartTimeZone = "UTC", End = new Models.TimeInfo { DateTime = nextMonday9AM.AddHours(1).ToUniversalTime(), TimeZone = "UTC" }, OriginalEndTimeZone = "UTC", Importance = Models.ItemImportance.Normal, Subject = "Recurring Event about Microsoft Graph API", Body = new Models.ItemBody { Content = "<html><body><h2>Let's talk about the Microsoft Graph API!</h2></body></html>", Type = Models.BodyType.Html, }, Location = new Models.EventLocation { Name = "Paolo's Office", }, IsAllDay = false, IsOrganizer = true, ShowAs = Models.EventStatus.Busy, Type = Models.EventType.SeriesMaster, Recurrence = new Models.EventRecurrence { Pattern = new Models.EventRecurrencePattern { Type = Models.RecurrenceType.Weekly, DaysOfWeek = new DayOfWeek[] { DayOfWeek.Monday }, Interval = 1, }, Range = new Models.EventRecurrenceRange { StartDate = nextMonday9AM.ToUniversalTime(), Type = Models.RecurrenceRangeType.EndDate, EndDate = lastDayOfMonth.ToUniversalTime(), } } }); var seriesInstances = CalendarHelper.ListSeriesInstances( calendar.Id, eventSeries.Id, DateTime.Now, DateTime.Now.AddMonths(2)); var singleEventToUpdate = CalendarHelper.GetEvent(calendar.Id, events[0].Id); singleEventToUpdate.Attendees = new List <Models.UserInfoContainer>( new Models.UserInfoContainer[] { new Models.UserInfoContainer { Recipient = new Models.UserInfo { Name = model.MailSendToDescription, Address = model.MailSendTo, } }, }); var updatedEvent = CalendarHelper.UpdateEvent(calendar.Id, singleEventToUpdate); CalendarHelper.DeleteEvent(calendar.Id, singleEvent.Id); CalendarHelper.DeleteEvent(calendar.Id, eventSeries.Id); return(View("Index")); }
public void OnAuthorization(AuthorizationContext filterContext) { #region | Version 1 | //if (filterContext == null) //{ // throw new CoreLevelException("Exception in CaterpillarAntiForgeryAttribute.OnAuthorization(AuthorizationContext filterContext)", new ArgumentNullException("filterContext")); //} //var httpContext = filterContext.HttpContext; //string cookieValue = httpContext.Request.Cookies[_headerName].Value; //string headerValue = httpContext.Request.Headers[_headerName]; //string formValue = headerValue ?? httpContext.Request.Form[_headerName]; ////AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request[_headerName]); //if (!string.Equals(cookieValue, formValue)) //{ // string requestContentType = filterContext.HttpContext.Request.ContentType.ToLower(); // if (requestContentType.Contains("json")) // { // JsonResultBase jrb = new JsonResultBase(); // jrb.Data = RedirectUrl; // jrb.ClientSideAction = ClientSideAction.Redirect; // JsonResult jr = new JsonResult(); // jr.Data = jrb; // filterContext.Result = jr; // } // else // { // filterContext.Result = new RedirectResult(RedirectUrl); // } // //throw new CriticalLevelException("HttpAntiForgeryException is cought. An attack might occur.", new HttpAntiForgeryException()); //} #endregion | Version 1 | var request = filterContext.HttpContext.Request; // Only validate POSTs if (request.HttpMethod == WebRequestMethods.Http.Post) { // Ajax POSTs and normal form posts have to be treated differently when it comes // to validating the AntiForgeryToken if (request.IsAjaxRequest()) { var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName]; var cookieValue = antiForgeryCookie != null ? antiForgeryCookie.Value : null; AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]); } else { new ValidateAntiForgeryTokenAttribute() .OnAuthorization(filterContext); } } }
public override void OnAuthorization(AuthorizationContext filterContext) { var request = filterContext.HttpContext.Request; try { //Ajax Requests string tokenInCookie = string.Empty; string tokenInForm = string.Empty; if (request.HttpMethod == WebRequestMethods.Http.Post) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { var antiforgeryToken = request.Headers.Get("AntiForgeryToken"); if (!string.IsNullOrEmpty(antiforgeryToken)) { tokenInCookie = antiforgeryToken.Split(':')[0].Trim(); tokenInForm = antiforgeryToken.Split(':')[1].Trim(); } AntiForgery.Validate(tokenInCookie, tokenInForm); return; } } } catch (HttpAntiForgeryException ex) { //Log filterContext.Result = new ContentResult() { Content = "Forbidden Content.You do not currently have permission to access the page you have requested. <br /> " + "If you feel this is incorrect," + "please contact your local admin.", }; Logger.LogError(ex, $"Exception in ValidateAntiForgeryToken for user {filterContext.HttpContext.User.Identity.Name}"); throw; } catch (Exception ex) { filterContext.Result = new ContentResult() { Content = "Forbidden Content.You do not currently have permission to access the page you have requested. <br /> " + "If you feel this is incorrect," + "please contact your local admin.", }; Logger.LogError(ex, $"Exception in ValidateAntiForgeryToken for user {filterContext.HttpContext.User.Identity.Name}"); throw; } // Only validate POSTs if (request.HttpMethod == WebRequestMethods.Http.Post) { var headerTokenValue = request.Headers[HTTP_HEADER_NAME]; // Ajax POSTs using jquery have a header set that defines the token. // However using unobtrusive ajax the token is still submitted normally in the form. // if the header is present then use it, else fall back to processing the form like normal if (headerTokenValue != null) { var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName]; var cookieValue = antiForgeryCookie != null ? antiForgeryCookie.Value : null; AntiForgery.Validate(cookieValue, headerTokenValue); } else if ((!request.FilePath.Contains("ExportToExcel")) && (!request.FilePath.Contains("ListOfCasesExportToExcel"))) { new ValidateAntiForgeryTokenAttribute() .OnAuthorization(filterContext); } } }
public MvcHtmlString AntiForgeryToken() { return(MvcHtmlString.Create(AntiForgery.GetHtml().ToString())); }
public ActionResult CreateSubSite(CreateSubSiteViewModel model) { switch (model.Step) { case CreateSiteStep.SiteInformation: ModelState.Clear(); // If it is the first time that we are here if (String.IsNullOrEmpty(model.Title)) { model.InheritPermissions = true; using (var ctx = PnPPartnerPackContextProvider.GetAppOnlyClientContext(model.ParentSiteUrl)) { Web web = ctx.Web; ctx.Load(web, w => w.Language, w => w.RegionalSettings.TimeZone); ctx.ExecuteQueryRetry(); model.Language = (Int32)web.Language; model.TimeZone = web.RegionalSettings.TimeZone.Id; } } break; case CreateSiteStep.TemplateParameters: if (!ModelState.IsValid) { model.Step = CreateSiteStep.SiteInformation; } else { if (!String.IsNullOrEmpty(model.ProvisioningTemplateUrl) && model.ProvisioningTemplateUrl.IndexOf(PnPPartnerPackConstants.PnPProvisioningTemplates) > 0) { String templateSiteUrl = model.ProvisioningTemplateUrl.Substring(0, model.ProvisioningTemplateUrl.IndexOf(PnPPartnerPackConstants.PnPProvisioningTemplates)); String templateFileName = model.ProvisioningTemplateUrl.Substring(model.ProvisioningTemplateUrl.IndexOf(PnPPartnerPackConstants.PnPProvisioningTemplates) + PnPPartnerPackConstants.PnPProvisioningTemplates.Length + 1); String templateFolder = String.Empty; if (templateFileName.IndexOf("/") > 0) { templateFolder = templateFileName.Substring(0, templateFileName.LastIndexOf("/") - 1); templateFileName = templateFileName.Substring(templateFolder.Length + 1); } model.TemplateParameters = PnPPartnerPackUtilities.GetProvisioningTemplateParameters( templateSiteUrl, templateFolder, templateFileName); } } break; case CreateSiteStep.SiteCreated: AntiForgery.Validate(); if (ModelState.IsValid) { // Prepare the Job to provision the Sub Site SubSiteProvisioningJob job = new SubSiteProvisioningJob(); // Prepare all the other information about the Provisioning Job job.SiteTitle = model.Title; job.Description = model.Description; job.Language = model.Language; job.TimeZone = model.TimeZone; job.ParentSiteUrl = model.ParentSiteUrl; job.RelativeUrl = model.RelativeUrl; job.SitePolicy = model.SitePolicy; job.Owner = ClaimsPrincipal.Current.Identity.Name; job.ProvisioningTemplateUrl = model.ProvisioningTemplateUrl; job.InheritPermissions = model.InheritPermissions; job.Title = String.Format("Provisioning of Sub Site \"{1}\" with Template \"{0}\" by {2}", job.ProvisioningTemplateUrl, job.RelativeUrl, job.Owner); job.TemplateParameters = model.TemplateParameters; model.JobId = ProvisioningRepositoryFactory.Current.EnqueueProvisioningJob(job); } break; default: break; } return(PartialView(model.Step.ToString(), model)); }
public RedirectResult RedirectToProvider(RedirectToProviderInputModel inputModel) { if (!ModelState.IsValid) { throw new ArgumentException( "Some binding errors occured. This means at least one Request value (eg. form post or querystring parameter) provided is invalid. Generally, we need a ProviderName as a string."); } if (string.IsNullOrEmpty(inputModel.ProviderKey)) { throw new ArgumentException( "ProviderKey value missing. You need to supply a valid provider key so we know where to redirect the user Eg. google."); } // Grab the required Provider settings. var settings = AuthenticationService.GetAuthenticateServiceSettings(inputModel.ProviderKey, Request.Url, Url.CallbackFromOAuthProvider()); // An OpenId specific settings provided? if (!string.IsNullOrEmpty(inputModel.Identifier) && settings is IOpenIdAuthenticationServiceSettings) { Uri identifier; if (!Uri.TryCreate(inputModel.Identifier, UriKind.RelativeOrAbsolute, out identifier)) { throw new ArgumentException( "Indentifier value was not in the correct Uri format. Eg. http://myopenid.com or https://yourname.myopenid.com"); } ((IOpenIdAuthenticationServiceSettings)settings).Identifier = identifier; } // Our convention is to remember some redirect url once we are finished in the callback. // NOTE: If no redirectUrl data has been provided, then default to the Referrer, if one exists. string extraData = null; if (RedirectUrl != null && !string.IsNullOrEmpty(RedirectUrl.AbsoluteUri)) { // We have extra state information we will need to retrieve. extraData = RedirectUrl.AbsoluteUri; } else if (Request != null && Request.UrlReferrer != null && !string.IsNullOrEmpty(Request.UrlReferrer.AbsoluteUri)) { extraData = Request.UrlReferrer.AbsoluteUri; } // Generate a token pair. var token = AntiForgery.CreateToken(extraData); // Put the "ToSend" value in the state parameter to send along to the OAuth Provider. settings.State = token.ToSend; // Serialize the ToKeep value in the cookie. SerializeToken(Response, token.ToKeep); // Determine the provider's end point Url we need to redirect to. var uri = AuthenticationService.RedirectToAuthenticationProvider(settings); // Kthxgo! return(Redirect(uri.AbsoluteUri)); }
public ActionResult CreateSubSite(CreateSubSiteViewModel model) { PnPPartnerPackSettings.ParentSiteUrl = model.ParentSiteUrl; if (model.Step == CreateSiteStep.SiteInformation) { ModelState.Clear(); // If it is the first time that we are here if (String.IsNullOrEmpty(model.Title)) { model.InheritPermissions = true; using (var ctx = PnPPartnerPackContextProvider.GetAppOnlyClientContext(model.ParentSiteUrl)) { Web web = ctx.Web; ctx.Load(web, w => w.Language, w => w.RegionalSettings.TimeZone); ctx.ExecuteQueryRetry(); model.Language = (Int32)web.Language; model.TimeZone = web.RegionalSettings.TimeZone.Id; } } } if (model.Step == CreateSiteStep.TemplateParameters) { if (!ModelState.IsValid) { model.Step = CreateSiteStep.SiteInformation; } else { if (!String.IsNullOrEmpty(model.ProvisioningTemplateUrl) && !String.IsNullOrEmpty(model.TemplatesProviderTypeName)) { var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[model.TemplatesProviderTypeName]; if (templatesProvider != null) { var template = templatesProvider.GetProvisioningTemplate(model.ProvisioningTemplateUrl); model.TemplateParameters = template.Parameters; } if (model.TemplateParameters == null || model.TemplateParameters.Count == 0) { model.Step = CreateSiteStep.SiteCreated; } } } } if (model.Step == CreateSiteStep.SiteCreated) { AntiForgery.Validate(); if (ModelState.IsValid) { // Prepare the Job to provision the Sub Site SubSiteProvisioningJob job = new SubSiteProvisioningJob(); // Prepare all the other information about the Provisioning Job job.SiteTitle = model.Title; job.Description = model.Description; job.Language = model.Language; job.TimeZone = model.TimeZone; job.ParentSiteUrl = model.ParentSiteUrl; job.RelativeUrl = model.RelativeUrl; job.SitePolicy = model.SitePolicy; job.Owner = ClaimsPrincipal.Current.Identity.Name; job.ApplyTenantBranding = model.ApplyTenantBranding; job.ProvisioningTemplateUrl = model.ProvisioningTemplateUrl; job.TemplatesProviderTypeName = model.TemplatesProviderTypeName; job.InheritPermissions = model.InheritPermissions; job.Title = String.Format("Provisioning of Sub Site \"{1}\" with Template \"{0}\" by {2}", job.ProvisioningTemplateUrl, job.RelativeUrl, job.Owner); job.TemplateParameters = model.TemplateParameters; model.JobId = ProvisioningRepositoryFactory.Current.EnqueueProvisioningJob(job); } } return(PartialView(model.Step.ToString(), model)); }
public void OnAuthorization(AuthorizationContext filterContext) { AntiForgery.Validate(); }
public ActionResult CreateSiteCollection(CreateSiteCollectionViewModel model) { if (model.Step == CreateSiteStep.SiteInformation) { ModelState.Clear(); if (String.IsNullOrEmpty(model.Title)) { // Set initial value for PnP Partner Pack Extensions Enabled model.PartnerPackExtensionsEnabled = true; model.ResponsiveDesignEnabled = true; } } if (model.Step == CreateSiteStep.TemplateParameters) { if (!ModelState.IsValid) { model.Step = CreateSiteStep.SiteInformation; } else { if (!String.IsNullOrEmpty(model.ProvisioningTemplateUrl) && !String.IsNullOrEmpty(model.TemplatesProviderTypeName)) { var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[model.TemplatesProviderTypeName]; if (templatesProvider != null) { var template = templatesProvider.GetProvisioningTemplate(model.ProvisioningTemplateUrl); model.TemplateParameters = template.Parameters; } } if (model.TemplateParameters == null || model.TemplateParameters.Count == 0) { model.Step = CreateSiteStep.SiteCreated; } } } if (model.Step == CreateSiteStep.SiteCreated) { AntiForgery.Validate(); if (ModelState.IsValid) { // Prepare the Job to provision the Site Collection SiteCollectionProvisioningJob job = new SiteCollectionProvisioningJob(); // Prepare all the other information about the Provisioning Job job.SiteTitle = model.Title; job.Description = model.Description; job.Language = model.Language; job.TimeZone = model.TimeZone; job.RelativeUrl = String.Format("/{0}/{1}", model.ManagedPath, model.RelativeUrl); job.SitePolicy = model.SitePolicy; job.Owner = ClaimsPrincipal.Current.Identity.Name; job.ApplyTenantBranding = model.ApplyTenantBranding; job.PrimarySiteCollectionAdmin = model.PrimarySiteCollectionAdmin != null && model.PrimarySiteCollectionAdmin.Principals.Count > 0 ? (!String.IsNullOrEmpty(model.PrimarySiteCollectionAdmin.Principals[0].Mail) ? model.PrimarySiteCollectionAdmin.Principals[0].Mail : null) : null; job.SecondarySiteCollectionAdmin = model.SecondarySiteCollectionAdmin != null && model.SecondarySiteCollectionAdmin.Principals.Count > 0 ? (!String.IsNullOrEmpty(model.SecondarySiteCollectionAdmin.Principals[0].Mail) ? model.SecondarySiteCollectionAdmin.Principals[0].Mail : null) : null; job.ProvisioningTemplateUrl = model.ProvisioningTemplateUrl; job.TemplatesProviderTypeName = model.TemplatesProviderTypeName; job.StorageMaximumLevel = model.StorageMaximumLevel; job.StorageWarningLevel = model.StorageWarningLevel; job.UserCodeMaximumLevel = model.UserCodeMaximumLevel; job.UserCodeWarningLevel = model.UserCodeWarningLevel; job.ExternalSharingEnabled = model.ExternalSharingEnabled; job.ResponsiveDesignEnabled = model.ResponsiveDesignEnabled; job.PartnerPackExtensionsEnabled = model.PartnerPackExtensionsEnabled; job.Title = String.Format("Provisioning of Site Collection \"{1}\" with Template \"{0}\" by {2}", job.ProvisioningTemplateUrl, job.RelativeUrl, job.Owner); job.TemplateParameters = model.TemplateParameters; model.JobId = ProvisioningRepositoryFactory.Current.EnqueueProvisioningJob(job); } } return(PartialView(model.Step.ToString(), model)); }
public HtmlForm(FormsPage page, object htmlAttributes) { _page = page; var htmlAttributesDictionary = new Dictionary <string, IList <string> > { { "class", new List <string> { "form", "formbuilder-" + page.Form.Name.ToLowerInvariant() } } }; if (page.FormRenderer.Horizontal) { htmlAttributesDictionary["class"].Add("form-horizontal"); } var htmlElementAttributes = page.Form.Attributes.OfType <HtmlTagAttribute>(); var action = (string)null; foreach (var attr in htmlElementAttributes) { if (attr.Attribute == "method") { continue; } if (attr.Attribute == "action") { action = attr.Value; continue; } IList <string> list; if (!htmlAttributesDictionary.TryGetValue(attr.Attribute, out list)) { htmlAttributesDictionary.Add(attr.Attribute, new List <string>()); } htmlAttributesDictionary[attr.Attribute].Add(attr.Value); } var dictionary = Functions.ObjectToDictionary(htmlAttributes); if (dictionary != null) { if (dictionary.ContainsKey("class")) { htmlAttributesDictionary["class"].Add((string)dictionary["class"]); } if (dictionary.ContainsKey("action")) { action = (string)dictionary["action"]; } } page.WriteLiteral("<form method=\"post\""); if (!String.IsNullOrEmpty(action)) { page.WriteLiteral(String.Format(" action=\"{0}\"", action)); } foreach (var kvp in htmlAttributesDictionary) { page.WriteLiteral(" " + kvp.Key + "=\""); foreach (var itm in kvp.Value) { page.WriteLiteral(itm + " "); } page.WriteLiteral("\""); } if (page.Form.HasFileUpload) { page.WriteLiteral(" enctype=\"multipart/form-data\""); } AddRendererSettings(); page.WriteLiteral(" data-culture=\"" + CultureInfo.CurrentCulture.Name + "\""); page.WriteLiteral(">"); page.WriteLiteral("<input type=\"hidden\" name=\"__type\" value=\"" + HttpUtility.HtmlAttributeEncode(page.Form.Name) + "\" />"); foreach (var field in page.Form.Fields.Where(f => f.IsHiddenField)) { AddHiddenField(field.Name, field.Id, field.Value == null ? String.Empty : field.GetValueAsString()); } if (!page.Form.DisableAntiForgery) { page.WriteLiteral(AntiForgery.GetHtml()); } }
protected new bool MapRequestFormData(BaseFormModel model) { if (Request.HttpMethod != "POST") { return(false); } // CSRF protection: If the anti CSRF cookie is present, a matching token must be in the form data too. const string antiCsrfToken = "__RequestVerificationToken"; if (Request.Cookies[antiCsrfToken] != null) { AntiForgery.Validate(); } foreach (string formField in Request.Form) { if (formField == antiCsrfToken) { // This is not a form field, but the anti CSRF token (already validated above). continue; } FormFieldModel fieldModel = model.FormFields.FirstOrDefault(f => f.Name == formField); if (fieldModel == null) { Log.Debug("Form [{0}] has no defined field for form field '{1}'", model.Id, formField); continue; } // TODO: validate if field is valid string (no injection etc) //string formFieldValue = Request.Form[formField]; List <string> formFieldValues = Request.Form.GetValues(formField).Where(f => f != "false").ToList(); try { fieldModel.Values = formFieldValues; } catch (Exception ex) { Log.Debug("Failed to set Model [{0}] property '{1}' to value obtained from form data: '{2}'. {3}", model.Id, fieldModel.Name, formFieldValues, ex.Message); ModelState.AddModelError(fieldModel.Name, ex.Message); } FormFieldValidator validator = new FormFieldValidator(fieldModel); string validationMessage = "Field Validation Failed"; if (!validator.Validate(formFieldValues, ref validationMessage)) { if (validationMessage != null) { Log.Debug("Validation of property '{0}' failed: {1}", fieldModel.Name, validationMessage); ModelState.AddModelError(fieldModel.Name, validationMessage); continue; } } } return(true); }
public static void ValidateToken(HttpContext context) { AntiForgery.Validate(); }
public string GenerateAntiForgeryToken() { AntiForgery.GetTokens(null, out var cookieToken, out var formToken); return(cookieToken + ":" + formToken); }
public override void Execute() { WriteLiteral("\r\n\r\n"); WriteLiteral("\r\n"); DefineSection("PackageHead", () => { WriteLiteral(" \r\n <script type=\"text/javascript\" src=\""); Write(Href("scripts/PackageAction.js")); WriteLiteral("\"></script>\r\n <noscript>"); Write(PackageManagerResources.JavascriptRequired); WriteLiteral("</noscript>\r\n"); }); WriteLiteral("\r\n"); // Read params from request var sourceName = Request["source"]; var packageId = Request["package"]; var versionString = Request["version"]; var packageSource = PageUtils.GetPackageSource(sourceName); var version = !versionString.IsEmpty() ? SemanticVersion.Parse(versionString) : null; WebProjectManager projectManager; try { projectManager = new WebProjectManager(packageSource.Source, PackageManagerModule.SiteRoot); } catch (Exception exception) { WriteLiteral(" <div class=\"error message\">"); Write(exception.Message); WriteLiteral("</div>\r\n"); return; } var updatePackage = projectManager.SourceRepository.FindPackage(packageId, version); if (updatePackage == null) { ModelState.AddFormError(PackageManagerResources.BadRequest); Write(Html.ValidationSummary()); return; } var package = projectManager.LocalRepository.FindPackage(packageId); // Layout Page.SectionTitle = String.Format(CultureInfo.CurrentCulture, PackageManagerResources.UpdatePackageDesc, package.GetDisplayName(), updatePackage.Version); var packagesHomeUrl = Href(PageUtils.GetPackagesHome(), Request.Url.Query); if (IsPost) { AntiForgery.Validate(); try { projectManager.UpdatePackage(updatePackage); } catch (Exception exception) { ModelState.AddFormError(exception.Message); } if (ModelState.IsValid) { Response.Redirect(packagesHomeUrl + "&action-completed=Update"); } else { Write(Html.ValidationSummary(String.Format(CultureInfo.CurrentCulture, PackageManagerResources.PackageUpdateError, package.GetDisplayName()))); } return; } WriteLiteral("\r\n"); Write(RenderPage("_PackageDetails.cshtml", new Dictionary <string, object> { { "Package", updatePackage } })); WriteLiteral("\r\n<br />\r\n<form method=\"post\" action=\"\" id=\"submitForm\">\r\n "); Write(AntiForgery.GetHtml()); WriteLiteral("\r\n <input type=\"hidden\" name=\"source\" value=\""); Write(sourceName); WriteLiteral("\" />\r\n <input type=\"hidden\" name=\"package\" value=\""); Write(packageId); WriteLiteral("\" />\r\n <input type=\"hidden\" name=\"version\" value=\""); Write(version); WriteLiteral("\" />\r\n\r\n <input type=\"submit\" value=\""); Write(PackageManagerResources.UpdatePackage); WriteLiteral("\" />\r\n <input type=\"reset\" value=\""); Write(PackageManagerResources.Cancel); WriteLiteral("\" data-returnurl=\""); Write(packagesHomeUrl); WriteLiteral("\" />\r\n <br /><br />\r\n</form>"); }
private static AntiForgery GetAntiForgery() { // AntiForgery must be passed to TestableHtmlGenerator constructor but will never be called. var optionsAccessor = new Mock<IOptions<AntiForgeryOptions>>(); var mockDataProtectionOptions = new Mock<IOptions<DataProtectionOptions>>(); mockDataProtectionOptions .SetupGet(options => options.Options) .Returns(Mock.Of<DataProtectionOptions>()); optionsAccessor .SetupGet(o => o.Options) .Returns(new AntiForgeryOptions()); var antiForgery = new AntiForgery( Mock.Of<IClaimUidExtractor>(), Mock.Of<IDataProtectionProvider>(), Mock.Of<IAntiForgeryAdditionalDataProvider>(), optionsAccessor.Object, new CommonTestEncoder(), mockDataProtectionOptions.Object); return antiForgery; }
public void GetTokens_ThrowsWhenNotCalledInWebContext() { Assert.Throws <ArgumentException>(() => { string dummy1, dummy2; AntiForgery.GetTokens("dummy", out dummy1, out dummy2); }, "An HttpContext is required to perform this operation. Check that this operation is being performed during a web request."); }