AllowHtml attribute not working on production - c#-4.0

I have a model that required that html be captured. I have added the [AllowHtml] attribute to the model property and it works correctly on my local server when debugging.
Once deployed to production however, it works correctly when executed on the production server (i.e. I remote onto the server and browse it there), but fails with the the usual "potentially dangerous blah blah blah " message when executed from any other machine.
So it seems to me that there is something to do with the location involved in the validation, or am I completely missing the boat.
Just to confirm, I have made no "special" changes to the web.config.
Please can someone explain why I am having this issue.
Model
[AllowHtml]
[Display(Name = "Overview")]
public string Overview { get; set; }
Controller
//
// POST: /Product/
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditFeature(BackOffice.Models.ProductFeature model)
{
if (ModelState.IsValid)
{
//insert the new product
}
//invalid model, return with errors
return View(model);
}
View
#model BackOffice.Models.ProductFeature
#using (Html.BeginForm("AddFeature", "Product", null, FormMethod.Post, new { role = "form", #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.Hidden("ProductID", #Model.ProductID)
<div class="modal fade" id="FeatureModal" tabindex="-1" role="dialog" aria-labelledby="FeatureModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add a Feature</h4>
</div>
<div class="modal-body">
<div class='form-group'>
<label class='col-lg-2 control-label'>Title</label>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Title, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Title)
</div>
</div>
<div class='form-group'>
<label class='col-lg-2 control-label'>Overview</label>
<div class="col-lg-10">
#Html.TextAreaFor(m => m.Description, 10, 40, new { #class = "ckeditor", id = "overview" })
</div>
</div>
</div>
<div class='clearfix'></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Add</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
}

There is a mis-match in the method names here. You have
#using (Html.BeginForm("AddFeature", "Product", null, FormMethod.Post, new { role = "form", #class = "form-horizontal" }))
{
}
But Your action method is called
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditFeature(BackOffice.Models.ProductFeature model)
{
}
Where is the AddFeature action method?

Related

redirect List<Data> to a view after user has submitting a form

I have a form where the user enter his/her details.
#using (Html.BeginForm("Create","Coupons"))
{
<div class="row">
<div class="col-sm-8">
<div class="page-header">Generer Coupon</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(m => m.Student)
#Html.DropDownListFor(m => m.Student, new SelectList(Model.Students, "Id", "Name"), "", new { #class = "form-control input-lg" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(m => m.Price)
#Html.TextBoxFor(m => m.Price, new { #class = "form-control input-lg" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(m => m.NumberOfCoupons)
#Html.TextBoxFor(m => m.NumberOfCoupons, new {#class = "form-control input-lg"})
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<button class="btn btn-success btn-lg">Generer</button>
</div>
</div>
}
I redirect the view to the Create Method on CouponsController
[HttpPost]
public ActionResult Create(CouponViewModel viewModel)
{
if (!ModelState.IsValid)
{
var model = new CouponViewModel
{
Students = _context.Students.ToList()
};
return View("Index", model);
}
for (int i = 1; i <= viewModel.NumberOfCoupons; i++)
{
var coupon = new Coupon
{
CouponNumber = viewModel.CouponNumber,
ValidationCode = viewModel.ValidationCode(6),
Price = viewModel.Price,
StudentId = viewModel.Student,
DateTime = Convert.ToDateTime(DateTime.Now.ToString("yy-MMM-dd ddd"))
};
_context.Coupons.Add(coupon);
_context.SaveChanges();
}
var coupons = _context.Coupons
.Where(c => c.StudentId == viewModel.Student)
.Include(s => s.Student)
.ToList();
TempData["viewModel"] = coupons;
return RedirectToAction("GetCoupons");
}
here is the view i receive the tempdata to display on the view
[HttpPost]
public ActionResult GetCoupons()
{
Coupon coupon = TempData["viewModel"] as Coupon;
return View("Print", (IEnumerable<Coupon>)coupon);
}
I have been stucked for like 3 days. I don't know where im wrong
There are a couple of problems with your example. But you can eliminate them if you do some things differently.
[HttpPost]
public ActionResult Create(CouponViewModel viewModel)
{
return RedirectToAction("GetCoupons", new { studentId = viewModel.Student });
}
First, your redirected action needs to be marked [HttpGet]. You can also avoid TempData if you pass the id on the query string, then perform the lookup in the redirected action.
[HttpGet]
public ActionResult GetCoupons(int studentId)
{
var coupons = _context.Coupons
.Where(c => c.StudentId == studentId)
.Include(s => s.Student)
.ToList();
return View("Print", coupons);
}
TempData isn't wrong but it won't persist on a refresh. Sometimes you will pass sensitive data which makes it useful then. Your cast to a single Coupon isn't quite what you want -- Cast to a collection instead.
[HttpGet]
public ActionResult GetCoupons()
{
var coupons = TempData["viewModel"] as IEnumerable<Coupon>;
return View("Print", coupons);
}

Why Spring Security is not working in my Spring Boot project?

MY QUESTION! WHY Once admin or users after login, they can not get on their dashboards. It updates the pages "/" or "/ home", but does not go
to UserDashboards or AdminDashboards?!
I am trying to configure Spring boot with Spring security and DB() for an application.
I have login-form in my home.jsp. User can login or registred in my site in modal window.
I will show you only a portion of home.jsp
<!-- Header -->
<li><spring:message code="nav.section.link5"/></li>
<c:if test="${email == null}">
<li><spring:message code="nav.section.link6"/></li>
<li><spring:message code="nav.section.link9"/></li>
</c:if>
<c:if test="${email != null}">
<li>${email}</li>
<li><spring:message code="nav.section.link10"></spring:message> </li>
</c:if>
<!-- modal login
================================================== -->
<div class="modal" id="modal-1">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-body">
<div class="btn-group btn-group-justified" role="group" aria-label="...">
<div class="btn-group" role="group">
<button type="button" class="btn btn-default active"><spring:message code="nav.section.link6"/></button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#modal-2" data-dismiss="modal"><spring:message code="nav.section.link9"/></button>
</div>
</div>
</div>
<div class="modal-footer">
<div align="center">
<ul class="sign-social-icon">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div class="or">
<p><spring:message code="modal.section.h3"/></p>
</div >
<form:form method="post" action="/userLogin" id="contact-formL" class="form-horizontal">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<div class="control-group controls">
<input type="email" class="reg" placeholder="<spring:message code="modal.section.h6"/>" name="email" id="emailL" value="${dto.email}">
</div>
<div class="control-group controls ">
<input type="password" class="reg" id="passwordL" placeholder="<spring:message code="modal.section.h7"/>" name="password" value="${dto.password}" >
</div>
<div class="sign form-actions">
<input role="button" type="submit" class="btn btn-primary btn-block" value="<spring:message code="nav.section.link6"/>">
</div>
</form:form>
<%--<div class="fmp">--%>
<%--<a><spring:message code="modal.section.h4"/></a>--%>
<%--</div>--%>
</div>
</div>
</div>
</div>
<!-- modal registration
================================================== -->
<div class="modal" id="modal-2">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-body">
<div class="btn-group btn-group-justified" role="group" aria-label="...">
<div class="btn-group" role="group">
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#modal-1" data-dismiss="modal" ><spring:message code="nav.section.link6"/></button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default active"><spring:message code="nav.section.link9"/></button>
</div>
</div>
</div>
<div class="modal-footer">
<div align="center">
<ul class="sign-social-icon">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div class="or">
<p><spring:message code="modal.section.h3"/></p>
</div>
<form:form action="/saveUser" modelAttribute="dto" name="myForm" id="contact-form" class="form-horizontal">
<div class="control-group controls">
<input type="email" class="reg" placeholder="<spring:message code="modal.section.h6"/>" name="email" id="email" value="${dto.email}">
</div>
<div class="control-group controls ">
<input type="password" class="reg" id="password" placeholder="<spring:message code="modal.section.h7"/>" name="password" value="${dto.password}" >
</div>
<div class="control-group controls">
<input type="password" class="reg" id="conf" placeholder="<spring:message code="modal.section.h8"/>" name="conf">
</div>
<div class="sign form-actions">
<input role="button" type="submit" class="btn btn-primary btn-block" value="<spring:message code="nav.section.link9"/>">
</div>
</form:form>
<div class="policy">
<spring:message code="modal.section.h5"/> </div>
</div>
</div>
</div>
</div>
This is my login method in HomeController.class:
#RequestMapping(value = "/userLogin", method = RequestMethod.POST)
public String updateOne(#RequestParam(required = true) String email, #RequestParam(required = true) String password, HttpServletRequest request) throws SQLException {
HttpSession session = request.getSession();
User user = userService.getByEmail(email);
System.out.println("проверка пароля и имейла с БД");
if (user != null && user.getPassword().equals(password)) {
session.setAttribute("email", user.getEmail());
System.out.println("ЛОГИНИТСЯ!!!");
if (userService.getByEmail(email).getRole().equals(Role.USER)) {
System.out.println("SALUT USER!!");
session.setAttribute("user", user);
return "redirect:/";
} else if (userService.getByEmail(email).getRole().equals(Role.MODERATOR)) {
System.out.println("SALUT MODERATOR!!");
session.setAttribute("moderator", user);
return "redirect:/";
} else if (userService.getByEmail(email).getRole().equals(Role.ADMIN)) {
System.out.println("SALUT ADMIN!!");
session.setAttribute("admin", user);
return "redirect:/";
}
}
return "redirect:/loginProblems";
}
The users and admin then has to open their dashboards(using click on button <li>${email}</li> in HEADER).
This is my DashboardController.class:
#Controller
public class DashboardsConroller {
#Autowired
UserService userService;
#Autowired
UserDataService userDataService;
#RequestMapping(value = "/dashboards", method = RequestMethod.GET)
public String selectDashboard(HttpServletRequest request) {
System.out.println("method selectDashboard!!");
HttpSession session = request.getSession();
User user = userService.getByEmail((String) session.getAttribute("email"));
System.out.println("СМОТРИ СЮДА = " + user);
if (userService.getByEmail(user.getEmail()).getRole().equals(Role.USER)) {
System.out.println("USER want to open dashboard!!");
session.setAttribute("user", user);
return "redirect:/userDash";
} else if (userService.getByEmail(user.getEmail()).getRole().equals(Role.MODERATOR)) {
System.out.println("Moderator want to open dashboard!!");
session.setAttribute("moderator", user);
return "redirect:/moderatorDash";
} else if (userService.getByEmail(user.getEmail()).getRole().equals(Role.ADMIN)) {
System.out.println("ADMIN want to open dashboard!!");
session.setAttribute("admin", user);
return "redirect:/adminDash";
} else {
System.out.println("LAST ELSE IS WORKING");
return "redirect:/home";
}
}
}
This is my showAdminDashboard() method in AdminDashController.class:
#PreAuthorize("hasAuthority('ADMIN')")
#RequestMapping(value = "/adminDash", method = RequestMethod.GET)
public ModelAndView showAdminDashboard(#ModelAttribute("myUserData") UserData myUserData,
#RequestParam(required = false) String firstName,
#RequestParam(required = false) String secondName,
HttpServletRequest request) throws SQLException {
...
}
This is my showUserDashboard() method in UserDashController.class:
#PreAuthorize("hasAuthority('USER')")
#RequestMapping(value = "/userDash", method = RequestMethod.GET)
public ModelAndView showUserDashboard(#ModelAttribute("myUserData") UserData myUserData,
#RequestParam(required = false) String firstName,
#RequestParam(required = false) String secondName,
HttpServletRequest request) throws SQLException, InstantiationException, IllegalAccessException {
...
return modelAndView;
}
This is my SecurityConfig.class :
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home", "/userLogin", "/dashboards", "/saveUser").permitAll()
.antMatchers("/adminDash").hasAuthority("ADMIN")
.antMatchers("/userDash").hasAuthority("USER")
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/")
.usernameParameter("email")
.passwordParameter("password")
.failureUrl("/loginProblems")
.permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/accountLogout"));
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
WHY Once admin or users after login, they can not get on their dashboards.
It happens because user wasn't authenticated properly, in fact for a Spring Security, user is still not authenticated.
When you're using Spring Security, it should authenticate users (by finding user in the database, comparing passwords, assigning roles and so on). But you're trying to authenticate users by your own code (in /userLogin).

Post to an external form from a controller in mvc5

I have a form in a mvc5 view with a button. I need to process this form in the controller and add a few more field values which is picked up from the controller and then posted to an external url.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Deal</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.First_Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.First_Name, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.First_Name)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Last_Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Last_Name, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Last_Name)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" name="save" />
<input type="submit" value="Register Deal" class="btn btn-default" name="submit" />
</div>
</div>
Controller
public ActionResult Create([Bind(Include = "Id,Name,Company,Telephone,Fax,Email,Title,Status,OpportunityAmount,First_Name,Last_Name,City,State,Country,Zip")] Deal deal, String submit)
{
if (ModelState.IsValid)
{
// do some processing and submit to another external form
}
}
Any thoughts on how we can accomplish this ?
One use case would be
if an username is provided the user then i would need to query from database the first last name, age etc and submit it to registration form of another site
You can post using Web Request Method. E.g.
public void post()
{
string URL = "http://";
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(URL);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
Stream reqStream = webRequest.GetRequestStream();
string postData = Request.QueryString; //you form data in get format
byte[] postArray = Encoding.ASCII.GetBytes(postData);
reqStream.Write(postArray, 0, postArray.Length);
reqStream.Close();
StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream());
string Result = sr.ReadToEnd();
}

Required Attribute not firing

The following is my class. I am trying to make a small login form. I have a class LoginApp which has username and password. Both I have made required.
[Required(ErrorMessage="This Is a required field")]
[Display(Name="User Name")]
public string userName { get; set; }
[Required]
[Display(Name = "PassWord")]
public string passWord { get; set; }
Following is my controller where i have used tryUpdateModel for checking.
public ActionResult Login(Models.LoginApp LA)
{
LoginApp LAPP = new LoginApp();
bool g = TryUpdateModel(LAPP);
if (ModelState.IsValid)
{
if (LA.userName == "admin" && LA.passWord == "admin")
return RedirectToAction("LoginSuccessful", new { userName = LA.userName});
else
return RedirectToAction("Index");
}
else
return RedirectToAction("Index");
}
Here is the view.
<div class="container">
#using (Html.BeginForm("Login", "Login"))
{
#Html.ValidationSummary(true)
<div class="row">
<div class="form-group ">
#Html.Label("User Name", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(Model => Model.userName, "", new { #class = "form-control" })
#Html.ValidationMessageFor(Model => Model.userName)
</div>
</div>
<br />
<br />
<div class="form-group ">
#Html.Label("PassWord", new { #class = "col-md-2 control-label" })
<div class="col-md-10 ">
#Html.PasswordFor(u => u.passWord, new { #class = "form-control" })
#Html.ValidationMessageFor(Model => Model.passWord)
</div>
</div>
<br />
<br />
<div class="form-group ">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log in" class="btn btn-default" />
<input type="button" id="btn" value="Reset" onclick="" class="btn btn-default" />
</div>
</div>
</div>
}
</div>
When I click the log in button without supplying the username or password it doesn't give me validation messages. Where I am going wrong.
You didn't include the validate.js and unobtrusiveon the page.
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
You should check if the ModelState.IsValid in the controller in order to ake the validation in back-end too (so in both side)

How to Localize Custom Module Content in Orchard CMS?

I had made some modules in my Orchard site using MVC 3 and EFW .I had also made contents using Orchard Cms like I made some static pages using CMS . But my module has dynamic data which user can add and change them using site admin area.But my question is that I had to localize my app but how ? I made enable Culture picker module and added po files of my desire language and added translations of every content of my site but when I change culture only my CMS content changes.my custom module which I made using MVC 3 and EntityFrameWork does not have any offect of site Culture how to localize my custom module contents ?
public class ContactUsController : Controller
{
DbEntities context = new DbEntities();
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult SaveContacts(FormCollection frmData) {
try
{
using (new TransactionScope(TransactionScopeOption.Suppress))
{
if (ModelState.IsValid == true)
{
Imidus_ContactUs ob = new Imidus_ContactUs();
ob.UserName = frmData["UserName"];
ob.Subject = frmData["Subject"];
ob.Message = frmData["Message"];
ob.Email = frmData["Email"];
context.Imidus_ContactUs.Add(ob);
context.SaveChanges();
return RedirectToAction("Success", "ContactUs");
}
}
}
catch (Exception ex) {
throw ex;
}
return View("Index");
}
public ActionResult Success()
{
return View();
}
}
<fieldset class="contact-form">
#using (Html.BeginForm("SaveContacts", "ContactUs", FormMethod.Post, new { id = "frmContact" }))
{
#Html.ValidationSummary(true)
<span class="errormsg"></span>
<label for="cname">
Name</label>
<div class="editor-field">
<input id="cname" name="UserName" minlength="2" type="text" required />
</div>
<div class="editor-label">
<label for="cemail">
E-Mail</label>
</div>
<div class="editor-field">
<input id="cemail" type="email" name="Email" required />
#* #Html.EditorFor(model => model.Email, new { Class = "input-xlarge" })
*#
</div>
<div class="editor-label">
<label for="csubject">
Subject</label>
</div>
<div class="editor-field">
<input id="csubject" name="Subject" minlength="2" type="text" required />
#* #Html.EditorFor(model => model.Subject, new { Class = "input-xlarge" })
#Html.ValidationMessageFor(model => model.Subject)*#
</div>
<div class="editor-label">
<label for="cMessage">
Message</label>
</div>
<div class="editor-field">
<input id="cMessage" name="Message" minlength="15" type="text" required />
#* #Html.TextAreaFor(model => model.Message)
#Html.ValidationMessageFor(model => model.Message)*#
</div>
<p>
<input type="submit" value="Submit" class="btn btn-primary block my-btn" />
</p>
}
</fieldset>

Resources