ValidateInput(false) vs AllowHtml - asp.net-mvc-4

I have a form that is used to create a memo, to do that I am using a rich text editor to provide some styling, this creates html tags in order to apply style. When I post that text, the mvc throws an error to prevent potentially dangerous scripts, so I have to specifically allow it.
I have found 2 ways of doing this, one is to decorate the controller method with [ValidateInput(false)] and the other is to decorate the ViewModel attribute with [AllowHtml]. To me, [AllowHtml] looks much nicer, but I have only found that approach used 1 time and the [ValidateInput(false)] seems to be the preferred way.
Which method should I use and what are the differences between the two?

ValidateInput and AllowHTML are directly connected with XSS security issues.
So let us first try to understand XSS.
XSS (cross-site scripting) is a security attack where the attacker injects malicious code while doing data entry. Now the good news is that XSS is by default prevented in MVC. So if any one tries to post JavaScript or HTML code he lands with the below error.
But in real time there are scenarios where HTML has to be allowed, like HTML editors. So for those kind of scenarios you can decorate your action with the below attribute.
[ValidateInput(false)]
public ActionResult PostProduct(Product obj)
{
return View(obj);
}
But wait, there is a problem here. The problem is we have allowed HTML on the complete action which can be dangerous. So if we can have more granular control on the field or property level that would really create a neat, tidy and professional solution.
That’s where AllowHTML is useful. You can see in the below code I have decorated “AllowHTML” on the product class property level.
public class Product
{
public string ProductName { get; set; }
[AllowHtml]
public string ProductDescription { get; set; }
}
So summarizing “ValidateInput” allows scripts and HTML to be posted on action level while “AllowHTML” is on a more granular level.
I would recommend to use “AllowHTML” more until you are very sure that the whole action needs to be naked.
I would recommend you to read the blog post Preventing XSS Attacks in ASP.NET MVC using ValidateInput and AllowHTML which demonstrates step by step about the importance of these two attributes with an example.

if use Bind Include best way is AllowHtml otherwise
you can use ValidateInput(false) to disable all Validaton in controll

Related

Looking for better way to use multiple roles in Blazor AuthorizeView component

I'm working on a small application that uses Blazor and Authentication / Authorization and for the most part the Roles based authorization is perfect. However, I have a couple of scenarios where I need to authorize multiple roles within the AuthorizeView component, and I'm not sure I'm doing it the best way. I'm trying to avoid hard coding the string values into the components, so I started by setting up a static class to manage the string values like so:
public static class Roles
{
public const string Admin = "Admin";
public const string CanManageClients = "CanManageClients";
public const string CanManageProjects = "CanManageProjects";
}
Now I can use these values anywhere I need them, and for standard attribute based authorization I extended the AuthorizeAttribute class to allow me to pass multiple values in as needed. Now i have an [AuthorizeRoles] attribute to use. No problem so far. I can decorate an entire page with something like this:
#attribute [AuthorizeRoles(Roles.Admin, Roles.CanManageClients)]
and the related method decoration as needed:
[AuthorizeRoles(Roles.Admin, Roles.CanManageClients)]
public void DoTheThing()
{
//Doing things
}
When it comes to the Blazor AuthorizeView component however, things get tricky. The Razor syntax isn't allowing me to chain multiple roles together or interpolate a string, so I found a workaround that gets the job done:
<AuthorizeView Roles="#rolesList">
<Authorized>
//View related code once authorized
</Authorized>
</AuthorizeView>
And the related code block that produces the comma separated string that the component expects:
#code {
string rolesList => $"{Roles.Admin}, {Roles.CanManageClients}";
}
This works like it's supposed to and gets me where I need to be, but it looks and feels hacky to me. I've avoided the dreaded magic string scenario, but I have an odd looking backing field in another part of the code that supports the component. I know I could solve this by moving to a policy based or claims based system, but that would honestly be way overkill for this little application as I only have a handful of use cases. Any feedback from the community would be greatly appreciated, maybe I'm not thinking of something and maybe this is just fine the way it is?
This may help you
<AuthorizeView Roles="#($"{Roles.Admin}, {Roles.CanManageClients}")">

What dependency injection pattern to use for a MessageProvider?

I have a ContactController where I set up a message in the TempData (this is to display a message in the screen after successful submission) and in the layout, there's a partial _Message.cshtml that is supposed to render the message, if any. Method signatures below:
List<Message> GetMessages(IDictionary<string, object> dictionary);
void SetMessage(IDictionary<string, object> dictionary, string body, MessageType type);
Initially I thought about having a MessageProvider dependency injected in the constructor. But then it occurred to me: What if I need do this in other controllers? Besides, for me to use it in the partial view, I need to resolve the implementation from the container which I think is an acceptable solution to use in a class that extends WebViewPage (considering I am not going to unit test it).
public MyCustomViewPage()
{
this.MessageProvider = DependencyResolver.Current.GetService<MessageProvider>();
}
public MessageProvider MessageProvider { get; set; }
But can we avoid the Service Locator anti-pattern using another dependency injection pattern?
I was thinking this MessageProvider has a good default implementation and since we might need to use this in more controllers in the future, this might be a good candidate for Ambient Context design pattern as per the book Dependency Injection in .NET by Mark Seemann.
This way, I would eliminate the potential problem of having to change other controller constructors in the future in case I happen to have to set messages in them, I would eliminate the need to use the Service Locator anti-pattern in the MyCustomViewPage constructor and my controller will still be testable.
I would then use the following code in partial view:
var messages = MessageProvider.Current.GetMessages()
And the following code in my controllers:
MessageProvider.Current.SetMessage("Message sent successfully.", MessageType.Success);
And in my test fixtures (if I would actually need another implementation):
MessageProvider.SetMessageProvider(otherImplementation);
Do you think this approach makes sense? Any downsides I might be missing?
To anyone who might be looking for the same answer in the future, I decided to use Ambient Context for this because of the reasons I mentioned in the quesiton.

What is the best practices to handle multiple form operation under same action in ASP.NET MVC4?

I have the following scenario in my ASP.NET MVC4 project using Razor Engine:
I have a view with at least 4 different forms.
I would like to handle all form POST under same action mapping.
Actually, the 4 forms post to different Route Mapping, as follow:
POST: /User/FilterRolesInUse/15
POST: /User/RemoveRoles/15
POST: /User/FilterRolesNotInUse/15
POST: /User/AddRoles/15
I would like to know if is it possible to handle all 4 form under the same Route Mapping, something where all form post to /User/Roles/15 and then the controller can distinguish which form was submitted. The concept is something like:
class UserController : Controller {
//
// POST: /User/Roles/
public ActionResult Roles(int? id, object form) {
return DelegateToFormLogic(id, form);
}
}
I just want to know if is it possible because I really want to keep URL consistent.
Any advice or suggestion are welcome.
I do not see any advantage to having a single action that performs multiple functions. In fact it will be confusing to anyone that has to support the code. I would get away from submitting forms and use Ajax methods in your web client (using JQuery ajax) to get the data you need for this view and for update/insert/delete actions. This way you do not have to post back the whole page to perform actions that will probably take place on just portions of the view which will result in a better performing page and a better user experience. Change your controller to a ASP.NET Web API controller and make those methods a REST API that uses consistent URL naming convention and use HTTP verbs to indicate the type of action being performed. You will end up 3 methods that serve the 4 you have now and it could look something like this (they correspond to the same order listed in the question).
GET: /api/Role/15?InUse=True
DELETE: /api/Role/15
GET: /api/Role/15?InUse=False
POST: /api/Role
Your controller would look like this.
class RoleController : ApiController {
public List<Role> Get(int id, boolean InUse) { ... }
public void Delete(int id) { ... }
public void Post(List<Role> roles) { ... }
}
This maintains a clear separation of concerns while also keeping a consistent and understandable URL convention.

How to use FluentValidation to display UI error for either or fields

I have an MVC 3 app which uses FluentValidation to express validation logic on some ViewModel objects.
One of the objects has two properties as follows:
[DisplayNameAttribute(UiConstants.Telephone)]
public string Telephone { get; set; }
[DisplayNameAttribute(UiConstants.Email)]
public string Email { get; set; }
The rule is that EITHER of these properties must be entered at the UI and I want the UI to display a validation message for at least one of the fields (Email) when the user hits Submit but without doing a PostBack.
I can get the validation to work with the following code in the validator
RuleFor(contact => contact.Email)
.Must((contact, email) => string.IsNullOrWhiteSpace(email) != string.IsNullOrWhiteSpace(contact.Telephone))
.WithMessage(ValidationConstants.EmailOrTelephone);
and this will display my validation error message at the UI, but only after a PostBack.
I have also used a Custom Validator as follows
Custom(contactUs =>
{
return string.IsNullOrWhiteSpace(contactUs.Telephone) && string.IsNullOrWhiteSpace(contactUs.Email)
? new ValidationFailure("Email", ValidationConstants.EmailOrTelephone)
: null;
});
but this behaves in the same way.
Will this not work the way I am hoping?
Is there another way to do the validator to get the error message to display in the UI without doing a PostBack?
I know that I could also use DataAnnotations but I specifically want to do this with FluentValidation.
Many thanks
Brian
You're looking for client-side validation - this isn't specific to FluentValidation or DataAnnotations. Both mechanisms will work server-side automatically (you have to wire FluentValidation up to do this automatically after model binding, or run it manually).
If you want client-side validation with ASP.NET MVC, you'll also have to wire that bit up. This blog entry may help.
One note though - your Custom validator won't work by default (you'd have to replicate that validation in jQuery on the client). Check out this article on FluentValidation; here's an excerpt that shows what validators should "just work" client-side without rewriting your own:
Note that FluentValidation will also work with ASP.NET MVC's
client-side validation, but not all rules are supported. For example,
any rules defined using a condition (with When/Unless), custom
validators, or calls to Must will not run on the client side. The
following validators are supported on the client:
*NotNull/NotEmpty
*Matches (regex)
*InclusiveBetween (range)
*CreditCard
*Email
*EqualTo (cross-property equality comparison)
*Length

Does dependency injection increase my risk of doing something foolish?

I'm trying to embrace widespread dependency injection/IoC. As I read more and more about the benefits I can certainly appreciate them, however I am concerned that in some cases that embracing the dependency injection pattern might lead me to create flexibility at the expense of being able to limit risk by encapsulating controls on what the system is capable of doing and what mistakes I or another programmer on the project are capable of making. I suspect I'm missing something in the pattern that addresses my concerns and am hoping someone can point it out.
Here's a simplified example of what concerns me. Suppose I have a method NotifyAdmins on a Notification class and that I use this method to distribute very sensitive information to users that have been defined as administrators in the application. The information might be distributed by fax, email, IM, etc. based on user-defined settings. This method needs to retrieve a list of administrators. Historically, I would encapsulate building the set of administrators in the method with a call to an AdminSet class, or a call to a UserSet class that asks for a set of user objects that are administrators, or even via direct call(s) to the database. Then, I can call the method Notification.NotifyAdmins without fear of accidentally sending sensitive information to non-administrators.
I believe dependency injection calls for me to take an admin list as a parameter (in one form or another). This does facilitate testing, however, what's to prevent me from making a foolish mistake in calling code and passing in a set of NonAdmins? If I don't inject the set, I can only accidentally email the wrong people with mistakes in one or two fixed places. If I do inject the set aren't I exposed to making this mistake everywhere I call the method and inject the set of administrators? Am I doing something wrong? Are there facilities in the IoC frameworks that allow you to specify these kinds of constraints but still use dependency injection?
Thanks.
You need to reverse your thinking.
If you have a service/class that is supposed to mail out private information to admins only, instead of passing a list of admins to this service, instead you pass another service from which the class can retrieve the list of admins.
Yes, you still have the possibility of making a mistake, but this code:
AdminProvider provider = new AdminProvider();
Notification notify = new Notification(provider);
notify.Execute();
is harder to get wrong than this:
String[] admins = new String[] { "joenormal#hotmail.com" };
Notification notify = new Notification(admins);
notify.Execute();
In the first case, the methods and classes involved would clearly be named in such a way that it would be easy to spot a mistake.
Internally in your Execute method, the code might look like this:
List<String> admins = _AdminProvider.GetAdmins();
...
If, for some reason, the code looks like this:
List<String> admins = _AdminProvider.GetAllUserEmails();
then you have a problem, but that should be easy to spot.
No, dependency injection does not require you to pass the admin list as a parameter. I think you are slightly misunderstanding it. However, in your example, it would involve you injecting the AdminSet instance that your Notification class uses to build its admin list. This would then enable you to mock out this object to test the Notification class in isolation.
Dependencies are generally injected at the time a class is instantiated, using one of these methods: constructor injection (passing dependent class instances in the class's constructor), property injecion (setting the dependent class instances as properties) or something else (e.g. making all injectable objects implement a particular interface that allows the IOC container to call a single method that injects its dependencies. They are not generally injected into each method call as you suggest.
Other good answers have already been given, but I'd like to add this:
You can be both open for extensibility (following the Open/Closed Principle) and still protect sensitive assets. One good way is by using the Specification pattern.
In this case, you could pass in a completely arbitrary list of users, but then filter those users by an AdminSpecification so that only Administrators recieve the notification.
Perhaps your Notification class would have an API similar to this:
public class Notification
{
private readonly string message;
public Notification(string message)
{
this.message = message;
this.AdminSpecification = new AdminSpecification();
}
public ISpecification AdminSpecification { get; set; }
public void SendTo(IEnumerable users)
{
foreach(var u in users.Where(this.AdminSpecification.IsSatisfiedBy))
{
this.Notify(u);
}
}
// more members
}
You can still override the filtering behavior for testing-purposes by assigning a differet Specification, but the default value is secure, so you would be less likely to make mistakes with this API.
For even better protection, you could wrap this whole implementation behind a Facade interface.