Placing MVC 4 login control on Home/index page - asp.net-mvc

First off I am new to MVC, I was a webforms guy...
I want to show my login control on my home/index page, but no matter what I do I run in to errors. I have tried various techniques and have gotten many errors with each technique, so I wont list them all here.
Right now I have it set that if Request.IsAuthenticated then show the username else show the login form. But the form is obviously looking at the home controller and nothing happens when I submit the login.
Any advice would be much appreciated. I have been dabbling for days on this.
Thanks :)
Here is the Code:
'#{
ViewBag.Title = "MyApp";
}
<p>Code for main Index Page here</p>
#model Application.Models.LoginModel
#{
ViewBag.Title = "Log in";
}
#if (Request.IsAuthenticated) {
<text>
Hello, #Html.ActionLink(User.Identity.Name, "Manage", "Account", routeValues: null, htmlAttributes: new { #class = "username", title = "Manage" })!
#using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" })) {
#Html.AntiForgeryToken()
Log off
}
</text>
} else {
<section id="loginForm">
<h2>Use a local account to log in.</h2>
#using (Html.BeginForm(new { ReturnUrl = "RedirectToAction" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
#Html.LabelFor(m => m.Password)
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</li>
<li>
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe, new { #class = "checkbox" })
</li>
</ol>
<input type="submit" value="Log in" />
</fieldset>
<p>
#Html.ActionLink("Register", "Register", "Account") if you don't have an account.
</p>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
</section>
}
'

you have to modify your form like this:
#using (Html.BeginForm("Login","Account",FormMethod.Post, new { ReturnUrl = ViewBag.ReturnUrl }))
the key is the "Login","Account" part, that tells the form to post the data to the login action of the account controller instead of the home controller. I fought with the same thing for a few hours then figured it out.
if the data does not post to the account controller (the controller that actually validates the username and password and logs the user in) it will never try to log them in.
reason is :
by default in the routeconfig.cs class sends any links or forms that do not specify an action and controller send all stuff to the Index action of the Home controller.
Hope this helps

You should use a Child Action:
In your controller:
[ChildActionOnly]
public ActionResult LoginForm()
{
return View("_LoginFormPartialViewHere");
}
Then in your homepage view:
#{ Html.RenderAction("LoginForm"); }
In your partial view for your login form, you can strongly-type the view for your login view model, but make sure to specify a different post action for your form than the default "postback" model. This action will handle the login and only the login (so not your homepage action).

Your problem here is that you are attempting to write code without actually understanding what it does. Without understanding what it does, you are simply left randomly changing things hoping to find something that works. This is a very poor way to write software.
Your problem is rooted in the fact that you don't understand that MVC is merely generating HTML, and without understanding what that HTML is supposed to be doing, you have little hope of randomly figuring this out.
First, MVC has no concept of a "login control". They're just HTML form fields, and they sit within an HTML form element. Those form fields are posted to your controller using standard HTML, which means you have to ensure your form action method is correct, and that the action url is correct.
Secondly, when those form fields are posted, you have to have an action method that will receive the post. If that action method is not the same as the action method used in the GET, then you will have to tell the BeginForm() helper where to post to.
In MVC, you can't think like Webforms and just assume everything gets done for you. You have to do everything yourself, and make sure every link, every action, every selector, every bit of javascript, etc.. is all correct. This is more work than WebForms, but it's also more powerful and more efficient.

Related

ViewModel data being passed in address bar

I have my change password controler.
The user changes the password and clicks submit.
I have my viewmodel of person p.
I am not passing it at all to my success page.
return View("succsessFulLogin");
And still I am getting
http://localhost:50010/Password/ChangePassword?AccountName=username&CurrentPassword=currentPassValue&NewPassword=newPassValue&NewPasswordCheck=newCheckPassValue
In the address bar
this is my code on the page:
#using (Html.BeginForm("ChangePassword", "Password", FormMethod.Get))
{
#Html.HiddenFor(model => model.AccountName)
<br />
<div>
<h4>#Html.LabelFor(m => m.CurrentPassword)</h4> #Html.PasswordFor(m => m.CurrentPassword, new { onkeydown = "capLock(event);" } ) #Html.ValidationMessageFor(m => m.CurrentPassword)
</div>
<br />
<div>
<h4>#Html.LabelFor(m => m.NewPassword)</h4> #Html.PasswordFor(m => m.NewPassword, new { onkeydown = "capLock(event);" }) #Html.ValidationMessageFor(m => m.NewPassword)
</div>
<br />
<div>
<h4>#Html.LabelFor(m => m.NewPasswordCheck)</h4> #Html.PasswordFor(m => m.NewPasswordCheck, new { onkeydown = "capLock(event);" }) #Html.ValidationMessageFor(m => m.NewPasswordCheck)
</div>
<br />
<p>
<button class="btn-lg" type="submit">#Global.SAVE</button>
</p>
}
I disagree with osman Rahimi.
Using HTTP POST is in no way more secure than HTTP GET! As long as you're passing everything as clear text over http, you can read anything passed to and from the server, even if it isn't shown in the address bar. If you want to check me yourself, all you have to do is download fiddler, check the request and responses your page generates and see for yourself.
The proper way to transmit passwords on the net is to make sure you're using SSL and hashing the passwords. I am by no means an expert on the subject, but I think you'll find need in these answers:
Securely Transfer User Entered Password
How should password be transfered for logon in Asp.net Identity
How to securely save and send login username/password?
when you are using HTTP GET the browser send data in URl and in this way you have limitation up to 2048 characters.
know more about HTTPGET and HTTPPOST
to keep your data secure and protected change your method To POST Like this :
#using (Html.BeginForm("ChangePassword", "Password" FormMethod.Post, null))
{}
then Add [HTTpPost] to your Action Method in your controller , like :
[HttpPost]
public ActionResult ChangePassword(yourmodel model){}

Second model in same view not posting to controller

With the help of several SO questions, I've figured out how to use two models on the same view, using the tuple form. At the top of my file is this:
#using Project.Models;
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
#model Tuple<Foo, Bar>
}
For the Foo stuff, it uses jQuery like this:
#Html.DisplayFor(tuple => tuple.Item1.ID)
and works fine. However, for my second model, it isn't displaying info, but is a submission form. Currently, this is what I have:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "createFoo", #action = "/api/Foo" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="editor-field">
#Html.TextAreaFor(tuple => tuple.Item2.Text)
#Html.ValidationMessageFor(tuple => tuple.Item2.Text)<br />
</div>
<input type="submit" value="Post Response" />
}
Mind you, this is mostly copy paste from other views since I'm new to MVC and it worked fine with other forms. For my FooController, I have this:
public void Post([FromBody] Foo foo)
{
Foo existingFoo = this.fooRepository.GetFoo(foo.ID);
if (existingFoo != null)
{
// throw error
}
else
{
System.Diagnostics.Debug.WriteLine("MESSAGE POSTING: " + foo.Text);
}
}
When submitting from the view, the received foo isn't null (checked in other tests), but the foo.text is empty. I've tried lots of different inputs and such, but I'm just so unfamiliar with the #Html.* functions and ASP.net-MVC in general that I'm not sure where I could be going wrong.
If you need to see my repository code let me know, but I doubt it'd have an effect on this. Thanks in advance for any help.
There are 2 issues I can see with your code above:
The way the Html helper will output your fields and how that feeds into your api post
Not having your ID in the controller.
1: Outputting a field like this (#Html.TextAreaFor(tuple => tuple.Item2.Text)) will give the field the name "Item2.Text". This is an issue as that is what gets passed on the post. You will get form data with Item2.Text:dfsdsgdfg. This won't match when your API controller tries to bind. So, try outputting the text field with a set name:
#Html.TextArea("Text", #Model.Item2.Text)
2: Your Id field is not in the form... thus it won't be sent. Try using a hidden field:
#Html.Hidden("ID", #Model.Item1.ID)
Also, just a clarification, this (#Html.DisplayFor(tuple => tuple.Item1.ID)) is not jQuery.

Will Using AntiForgeryToken sufficient to cover the authorization rule in a POST action method

Will Using AntiForgeryToken covers the authorization rule in a POST action method
I have the following Create.cshtml view for creating a new Order:-
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<fieldset>
<legend>Create New Order</legend>
<ol>
<li>
#Html.LabelFor(m => m.OrderName)
#Html.TextBoxFor(m => m.OrderName)
</li>
<li>
#Html.LabelFor(m => m.OrderType)
#Html.TextBoxFor (m => m. OrderType)
</li>
<li>
#Html.LabelFor(m => m.OrderDate)
#Html.TextBoxFor(m => m. OrderDate)
</li>
</ol>
<input type="submit" value="Create" />
</fieldset>
}
The above view will be rendered when calling the following GET action method:-
[Authorize (Roles="customerservice")]
public ActionResult Create()
{
return View("Create");
}
and the POST action method is:-
//
// POST: /Create
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize (Roles="customerservice")]
public ActionResult Create(Order r)
{
// Code goes here
return View(model);
}
Now my question is as follow:-
since i am using the Antiforgery token in my view , then i will guarantee that any valid call to the "POST:/ Create" is done; from the application itself + when the user is inside the Create view, which means that the user is under the customerservice Role.
So does this means that if i remove the authorized attribute from the POST Create action method, then i am still secure? since if the application receive a "POST: Create" request then this means that the user is already authorized from the "Get: /Create" action method and that the request was sent from the Create view?
Any comment about the above question.
Best Regards
AntiForgeryToken consist from three items:
Attribute for action
Helper method in view
Cookie
AntiForgeryToken is not unique per each request, so if user is not logged, this is potentially risk.

MVC4 Razor Looses UserID if Unbound

I'm creating some user profile edit forms in MVC4 at the moment and for testing I was rendering the UserId property into a readonly textbox on the form like this:
<li>
#Html.LabelFor(model => model.UserId)
#Html.TextBoxFor(model => model.UserId, new { #readonly="readonly"})
</li>
As I'm nearing completion of the edit form I removed this textbox as it's just using up real estate. Once I had done this the model sent back to the controller when saving had the integer default value of 0 and then the Entity Framework blows up as it cannot update any rows. So I added this to the form:
<li>
#Html.HiddenFor(model => model.UserId, new { #readonly="readonly"})
</li>
Is this a safe move? Should I be using the ViewBag for things like this? On the profile details page I render an edit button like this:
#Html.ActionLink("Edit", "Edit", new { id=Model.UserId })
Meaning that the UserId is rendered in the link. Is this safe and secure or do I need to rethink how I move the models and ids around the UI?
TIA,
Is this a safe move?
This will do the job of sending the id to the server. Just get rid of the readonly="readonly" attribute which makes very little sense for a hidden input.
Should I be using the ViewBag for things like this?
This doesn't change anything in terms of security. Any user could still put whatever id he wants. Whether you are using a hidden field or an ActionLink you are still sending the id as plain text to the server and anyone could forge a request and put whatever id he wants. So if you site uses some form of authentication you must absolutely check on the server side that the id that you received actually is a resource that belongs to the currently authenticated user before attempting to perform any actions on it. Otherwise some authenticated user could supply the id of a resource that belongs to another user and be able to update it. Of course that's just a hypothetical scenario, it's not clear at all if this is your case and whether this id needs to be secured.
If UserId is sensitive, then there are other options
Keep UserId server side only with Session state (if your architecture allows for Session)
Put it in an encrypted cookie. Note as per Darin, that these can be compromised.
If it isn't sensitive, then your HiddenFor is fine - post it back with the rest of the form.
Don't put it in your ActionLink Querystring unless this is part of your route (i.e. /Controller/Action/id)
I would strongly suggest using ValueInjecter. Here is a code snippet doing the same thing
[HttpGet]
public new ActionResult Profile()
{
var model = new ProfileModel();
model.InjectFrom<UnflatLoopValueInjection>(this.GetCurrentUser());
return View(model);
}
[HttpPost]
public new ActionResult Profile(ProfileModel model)
{
if (ModelState.IsValid)
{
this.GetCurrentUser().InjectFrom<UnflatLoopValueInjection>(model);
try
{
_userService.SaveOrUpdate(this.GetCurrentUser());
TempData["Success"] = "User was successfully updated.";
return RedirectToAction("Profile");
}
catch (Exception)
{
ModelState.AddModelError("Exception", "Unexpected error");
}
}
return View(model);
}
And here is the view...
#using (Html.BeginForm("Profile", "Account", FormMethod.Post, new { #class = "form-horizontal" }))
{
#Html.ValidationSummary(true, "Unable to update profile. Please correct the errors and try again.", new { #class = "alert alert-block alert-error" })
#Html.EditorForModel()
<div class="form-actions">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
}

asp mvc fine grained view permission

I am build ASP MVC 4 web application and I need to create fine-grained permission on my views.
It means I need to show some actions to some users depend on their role, the data type request and other authorization rules.
On the controller side I put Authorize attribute where appropriate and create fine-grained code like so:
public ActionResult Index() {
List<Survey> surveys;
if (MyUser.IsSuperUser) {
surveys = surveyRep.AllSurveys.ToList();
}
else {
surveys = surveyRep.VisibleSurveys.ToList();
}
return View(surveys);
}
Because I'm building multi-tenant application any user who is not super user see only the "visible" surveys. Super user always see everything.
The problem now is how to create the same thing on the view side, without duplicating logic (DRY).
Currently when a user that is not super user and has only one tenant link to it I use this razor view logic:
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Survey</legend>
#if (!MyUser.IsSingleTenant) {
<div class="editor-label">
Tenant
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.TenantID, ...
#Html.ValidationMessageFor(model => model.TenantID)
</div>
}
MyUser return the currently logged in use and IsSingleTenant indicate if she only link to single tenant.
I'm afraid this will make my views messy with a lot of "if-then" logic.
How do other people solve this?
Thank you,
Ido.
There's nothing wrong with this approach. You could just put those sections in partial views to make it more readable:
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Survey</legend>
#if (!MyUser.IsSingleTenant) {
#Html.Partial("Tenant")
}
...
</fieldset>
}

Resources