Having password field optional only when editing - asp.net-mvc

I'm new to ASP.NET MVC, and I have this issue.
So, my model have a password attribute, when creating should be required, but when editing it should be optional, so you only change the password if you want to, but I don't know how to let it be optional if I mark it with required in the model. What should I do?
The best solution is to have a different view for changing the password?
I appreciate your help, thanks!
[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }

Either create a separate view model, or in your controller code check if its there, if not use ModelState.AddError("fieldName", "PAssword is required")

Related

Issue with HTML symbols in MVC Password Inputs (.NET Bug??)

Had a user include a "<" in their password. This of course isn't allowed and was causing a Post-Back crash. What threw me was "<" was allowed in other input boxes on my site.
Traced the problem down to the fact that it was because the Password box was being treated like a Password box using DataType.Password. If I commented out that DataType attribute, it works (but of course displays the password on the screen as I'm typing)
Doing some research and Testing, I found 2 possible solutions but I can't tell the difference between the two other than Method # 2 breaks the UI style and looks ugly
Method #1 ... Modify the Model...
[Required]
[Display(Name = "Password")]
[AllowHtml]
[DataType(DataType.Password)]
public string UserPassword { get; set; }
#Html.EditorFor(model => model.UserPassword ....
This option makes me nervous because I really don't want to allow HTML code in any of my inputs.
Method #2 ... Modify the View
[Required]
[Display(Name = "Password")]
public string UserPassword { get; set; }
#Html.PasswordFor(model => model.UserPassword ....
This makes me nervous because I'm relying on any views that display this model to have been done correctly and not present the password in plain text.
So my questions are:
Why does MVC\Razr seem to handle HTML just fine for a normal text box but chokes when you flag it as a Password DataType?
Which of the two methods is the Best practices and safest? (Is their a 3rd option?)
Thanks

How to handle Veracode error for MVC's Model's property for a password field?

I have a model for login logic. It contains a property called Password:
[Required(ErrorMessage = " ")]
[DataType(DataType.Password)]
public string Password { get; set; }
When Veracode scans the model it produces the following error:
CWE-316: Cleartext Storage of Sensitive Information in Memory
My view is generating the Password field as follows:
#Html.EditorFor(x => x.Password}
Then, along the line in the model, I'm using the following Windows Authentication logic to check if the user is a windows user:
DirectoryEntry de = new DirectoryEntry("LDAP://" + System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName, username, password, AuthenticationTypes.Secure);
The above class' constructor requires password as a string.
What would be the best solution that could fix the Veracode problem and allows me to use the logic I already have?
The solution was an easy one. I just have to change the declaration Password to UserIdnt.
Now Veracode doesn't recognize it as a security threat and let it go

Should I use data annotations in domain model too? ASP.NET MVC

I am a newbie in ASP.NET MVC, and something made me confused.
I am creating a login/registration web-app, and when I came to confirm password, I was a bit confused. I surely don't want confirm password column in my database. So for that reason, I use ViewModel. And I use data annotations for validation in my ViewModel. So there is no need to write any validation code in my Domain Model.
But when Entity Framework creates a table from my Domain Model object, from where will it get information for example about how many characters should username take? If I used data annotations in my domain model, I would write MaxLength or something.
Should I validate data in domain model too?
You client side validation can be taken care of using Data Annotations on your View Model and include jQuery validation script in your View.
So in your View Model, you can set minimum password length restriction like this:
using System.ComponentModel.DataAnnotations;
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
Of course, this is only for client side validation, for server side validation, you have to validate the data in your controller, but i don't believe you have to use data annotation on your domain model.
So in your controller, you can validate the data passed through like this
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model)
{
//checks for data passed through, if somehow people bypasses client side validation
if (ModelState.IsValid)
{
//continue
}
//validation failed, return to view
return View(model);
}
ModelState.IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process. ---- what does this do : ModelState.IsValid

Different validation on insert and edit

I'm using DataAnotation for validation and i need disable it of in some cases.
F.E. on create i need user insert password and confirmation, but for edit it can stay empty and not changed.
I have this model:
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[DisplayName("Re-enter Password")]
[Compare("Password", ErrorMessage = "The password and confirmation do not match.")]
public string PasswordControl { get; set; }
Enought vould be disable required on password on edit.
AFAIK, there are two ways, either will work.
Use different model for edit and insert. I prefer and use this one in my application. It's easy and future proof(Edit and insert models and rules may be quite different).
Customize a ValidationAttribute and override IsValid method. Use some context such as IsEdit field of your model. It can be used since MVC3. See the "Model Validation Improvements" part of this article http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx

Error while using Remote Property of DataAnnotation?

I am having a problem using the remote property of the data-anotation.
I am having a model for user which stores the data:
[DataType(DataType.EmailAddress,ErrorMessage="please enter valid email")]
[DisplayName("Email Address")]
[Required(ErrorMessage = "Email is Required")]
[Remote("CheckUniqueEmail","User",ErrorMessage="An account with this email address already exists.")]
public string Email { get; set; }
and I am checking the distinct user email while creating the new one...
When I try to login with the email and password in the different controller, it still calls the Remote and checks for the unique email...
I think I have to exclude the email and password property in the Login controller - but I don't know how.
you need to use 2 different view models, one for creating an account and one for logging in.
You should use another model for logging in at LoginController.
These validations will be used everywhere you use this model.
You can also use the MetadataType to reuse the same base model and apply different validations. Example Here.

Resources