Allow a user to login/signin between actions - asp.net-mvc

I have a requirement, where we allow a user to access a URL without logging in until a certain point.
For example:
OnlineBooking/Services. They can select the services, this populates the viewmodel and then brings up a confirm view OnlineBooking/Confirm allowing a user to add an email address etc. Which then generates a ViewModel.
My question is, how can I check the user exists, if it does. Redirect to the login view (Account Controller - Login Action), allow them to login, then redirect back to this action without losing the viewmodel in this action? This may not even be possible, if not how can I achieve this?
Thanks for any advice.
Example:
public async Task<IActionResult> Confirm(BookingViewModel bookingViewModel)
{
try
{
var matchedUser = await _userManager.FindByEmailAsync(bookingViewModel.Email);
if (matchedUser == null) //User does not have an existing account, so register them.
{
//This is fine
}
else
{
//Need to redirect to login, then back to here without losing the viewmodel
}
}

My question is, how can I check the user exists, if it does. Redirect to the login view (Account Controller - Login Action), allow them to login, then redirect back to this action without losing the viewmodel in this action
My personal preference would be to not even redirect the user. If you need them to login, popup a dialog asking them to login. Once the user is logged in (ajax), enable the button to continue..

Not sure if it's the best practice, but what about storing the View Model in the session before you redirect to the login page? Then at the beginning of the confirm action, check if that session variable exists.
Session variables can be set like this:
Session["MyViewModel"] = viewModel;
and retrieved like so:
MyViewModel viewModel = (MyViewModel)Session["MyViewModel"]

Related

Force a user to re-enter credentials before submit

Using MVC5, i have an application which a user must be logged into, and then can perform standard actions on some data (create, edit, delete).
I would like to add a credentials prompt, whenever a certain task if performed. So say for example a user is editing a row of data. I want them to be prompted to enter their login credentials again when they hit the Save button, before the row is updated. To be clear, they are ALREADY logged in, i just want to force them to re-confirm their credentials before being allowed to save.
How can i do this in the controller? I want a seperate screen/popup to show, asking for username and password (which will then be checked to ensure correct user credentials) before allowing update of the data.
I looked at creating a new method in the controller, which is passed a username and password, which looks after checking the users credentials again. But how do I go about calling this from the Edit screen, when I also need a popup to appear? Do i go down the route of adding a hidden div on the Edit view, which shows when the user clicks the Save button, and it then calls the method?
Generally, you're expected to attempt a solution, first. Then, if you run into specific issues, you can ask a question about those specific issues. I will tell you that this should be relatively straight-forward. All you need is for the user to re-enter their password. Just add a password input to your edit form and bind it to something on your view model, or you can simply bind it directly to an action parameter, in addition to your view model:
[HttpPost]
public ActionResult MyAction(MyViewModel model, string password)
If you want it to be done in a popup, simply include the popup HTML within the form (so the that the input in the popup will be part of the form) or you'll need to use JavaScript to set another input within the form, which would be bound to either a view model property or action param. Either way, the point is that the password should be posted along with the rest of the form data.
Once inside your post action, you can verify the password by manually:
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
var verifyPassword = UserManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash, password);
if (verifyPassword == PasswordVerificationResult.Failed)
{
ModelState.AddModelError("", "Password incorrect.");
// If password is incorrect, ModelState will be invalid now
}
if (ModelState.IsValid)
{
// save posted data
}
It sounds like you'd ideally want an action which you can call asynchronously from the client. While this can take the form of a standard MVC controller action, you may want to consider building this into a Web API controller (Generally we would use Web API controllers to serve up non-HTML responses). You can read more about Web API in many places on the web so I won't go into that now, but let's say you have a HttpResponseMessage result method which looks like this:
[HttpPost]
public HttpResponseMessage CheckCredentials(string username, string password)
{
// Check user credentials and return either one of the following results:
// If credentials valid
return Request.CreateResponse(HttpStatusCode.OK);
// If not valid
return Request.CreateErrorResponse(HttpStatusCode.BadRequest);
}
Using this pattern you could return a '200 OK' response for valid credentials and a '400 Bad Request' for invalid credentials.
As you already stated, you could have the HTML content required for authentication prompt hidden on the page. When the user performs an action which requires authentication, you could render the popup. When the user submits the popup you could fire off an asynchronous request to the Web API endpoint which you created earlier. Depending on the response you get back, you either proceed with the task or prompt for credentials again with an error message.
Obviously as you'd be sending user credentials over a we request, make sure you're making use of HTTPS.
EDIT:
As Chris mentioned below, this solution leaves your 'quick check' in the hands of the client. While this is fine when you simply want to provide a way to stop the user from easily carrying out an action without re-entering their credentials, you should not rely entirely on it.
You could store the username and password as hidden fields and include them with your main synchronous POST. This would allow you to check that the user entered valid credentials from the server.

Prevent access to page based on Authentication

I have an ASP.Net MVC 4 Website. When I started this site I had little to no web programming experience, and I don't believe I set up all of it appropriately.
I have pages, such as Home, Login, Register, which I consider public,
pages like, VerifyPIN and AccountCreated, which I consider internal
and pages like Dashboard and Profile, which are private.
I feel public pages should be accessed by anonymous users, but Login and Register should not be accessible once a user logs in.
Internal pages I want to only be available upon server redirect and never through the browser, aka I don't want a user to be able to type in www.MySite.com/AccountCreated.
And private pages are for a logged in user only.
I feel I have private pages working fine, but I don't know how to limit access to the other pages as described above. Perhaps my notion to not allow a logged in user to access the log in page is miss-found.
My site is relatively small due to the ajax nature of the site. I use [AllowAnonymous] on all public pages but then a logged in user can still access those and I am not sure how to prevent that.
My questions are,
How can I prevent a user from accessing a page via the address bar (www.MySite.com/AccountCreated)
How can I prevent access to a [AllowAnonymous] page once a user has logged in.
EDIT
Is it normal to prevent logged on users from accessing certain anonymous pages, such as login?
You may always check if user is already logged in. If he did, he will be redirected to another page:
public ActionResult AccountCreated(some params)
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index")
}
else
{
// login logic here
}
}
You may also check it directly in View:
#if (Request.IsAuthenticated)
{
<span> You are already logged in</span>
}
else
{
//Login form here
}
well for your first question you can use the [Authorize] action filter.
For your other question, I guess you will have to write your own implementation. You will need to create a new IAuthorizationFilter and use it instead of [AllowAnonymous]
Just some ideas(didn't try them actually).
For question 1 - if AccountCreated is an action that means that the registration form actually POSTs to that URL - i.e. It is accessible from outside. I suggest you apply an HttpPost attribute to it so it will process only POST requests - there is not much you can do here
For point two you can do something like this in your action method
if (HttpContext.User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
else return View();
Just a thought, Signout user when a user goes to Login or Register page .
Hope you have not provided any link on private pages for a user to go to login or Register
page or check if user is authenticated redirect it to Home page, frankly you can not stop a user to write a URL and pressing the enter button, or just give a notification that You'll be logged out if you proceed to whatever page.

asp.net mvc: TempData and AuthorizeAttribute

As a followup to this question, I'm wondering what's happening to my TempData.
Scenario 1:
user logs in
user provides email address
user receives email with validation code
user clicks on validation url
user is validated
success msg is displayed via TempData set in Validate action
Scenario 2:
user logs in
user provides email address
user logs out/times out
user receives email with validation code
user clicks on validation url
user is validated
success msg is not displayed via TempData set in Validate action
Now, I don't see a reason for the user to be logged in to validate. In Scenario 1, I put a "Success" message in TempData, and return RedirectToAction("Index"). Index action has an AuthorizeAttribute - if they're not logged in, they're redirected to the login screen (seperate controller).
I would like the login screen to display my message, but TempData appears to get cleared in this scenario. Am I misunderstanding the TempData lifecycle? Does it only apply to requests within the same controller?
The problem is that the AuthorizeAttribute is introducing another redirect into the cycle if the user is not logged in. You are redirecting the user to another action then, if the user is not logged in, the AuthorizeAttribute redirects them to the login page. TempData only lives over one request cycle, so the extra redirect (request) is emptying it and it isn't available on the login page.
You might consider just putting it in the Session directly instead of the TempData front-end to the Session. It should still be there as long as the Session lives.
[Authorize] introduces an extra redirect, which clears the TempData (Tvanfosson has explained the details). So for this to work, you can use a flag on the method you redirect to, for example
return RedirectToAction("Confirm", new { status = "Success!" });
(given that you have the following route and action method declared:)
routes.MapRoute("Confirmation",
"Account/Confirm/{status}",
new { controller = "Account", action = "Confirm", status = "" });
public ActionResult Confirm(string status)
{
return View(status);
}

How to create a view that is not accessible directly but can only be redirected to?

I'm currently working on the user registration in my project. After the registration is done I wish to show some confirmation to the user. I decided to create another view. That's fine.
Now, if after the registration I just return the view like:
public class MyController : Controller
{
[AcceptVerbs (HttpVerbs.Post), ValidateAntiForgeryToken]
public ActionResult Registration (FormCollection form)
{
/* Some logic goes here */
return View ("ConfirmationView");
}
}
Everything is working as desired. No changed url in the title bar. But... If I click the refresh button, the browser will submit the data from the form again which I do not want.
Then I decided to create a separate action, but that means it will produce a new url in the address bar. I do not want the user to click refresh now because this view will not be able to sensibly display the confirmation information again. Is there any way to make an action not accessible directly? Or at least any way to determine whether it was called directly or by redirection? In the latter case I would just take the user away from that page to maybe the home page.
Any way to accomplish this?
So I found the solution myself.
One can use TempData to detect the repeated or external action calls.
public class MyController : Controller
{
[AcceptVerbs (HttpVerbs.Post), ValidateAntiForgeryToken]
public ActionResult Registration (FormCollection form)
{
/* Some logic goes here */
TempData["RedirectCall"] = true;
return RedirectToAction ("Confirmation");
}
[AcceptVerbs (HttpVerbs.Get)]
public ActionResult Confirmation ()
{
if (TempData["RedirectCall"] == null)
return RedirectToAction ("StartPage", "Home");
return View ();
}
}
Nice and simple. :)
One way to solve your problem is to attach a guid or similar type of "random" data to a user session, and check for a valid session when the page is requested. If there is none, you redirect to a page saying that this url is not available at the moment, and that the user will soon be redirected (and then redirect to home after 5 seconds or so using js).
Roughly it would work like this:
When the user is registered, a session cookie is created with for example a GUID. The GUID is also stored in a database table, in which you have one column for the UserID primary key and one for the GUID. You also create an authentication cookie, thus logging the user on to your site.
When all datacalls etc are done, the user has been successfully registered and so on, you redirect to the confirmation page.
When the confirmation page is loaded, the user is automatically logged on (because you created the authentication cookie in step 1). You can then check for a row in the UserID-GUID table corresponding to the logged on user.
a) If there is such a row, you delete the row, and display the confirmation page with all the information.
b) If there is no such row, you display the error message and redirect. As you deleted the row when you showed the message the first time, the user will not be able to access the confirmation page again.
Note: If you use this approach (or some other that makes the confirmation page available only once) you should make sure that it is clearly stated on the confirmation page that the user won't be able to access that page again.
if(Request.UrlReferrer == null)
{
return RedirectToAction("Index");
}

Redirect to Login Page on some condition of session check

In C# with MVC, i want to write a common utility or class in which if a particular conditoin fails need to redirect to login page.
For ex.: When the user logged in to the website, userid will be added to session. To Access the "ManageUsers" page, the user should be logged in as admin, else i need to redirect to Login page. i need to check this condition in some of the other similar pages also. i dont want to check either the user is admin or normal user while login. i need to check this in common class.
Any suggesstions?
Actually I think this is not particularly good behavior for an application. I think you ought to disable (or hide) any actions that a user is not able to perform. In the case where the user hand-enters a URL, or uses a bookmark from when they had the privilege, show an error message rather than redirecting to the login page.
Imagine you're a user who is logged into your application. You click on a user interface element and it looks like you've been logged out. You have no way of knowing that you weren't supposed to use it. Disabling/hiding the element prevents this scenario from occurring for most users. Redirecting to an error gives valuable feedback to the user as to why the action they took did not result in what they expected.
I use a custom attribute derived from AuthorizeAttribute to achieve this effect. If a user isn't logged in, it redirects to the login page. If they are logged in, but not sufficiently privileged, it displays a suitable error view.
This already exist in ASP.NET MVC with the Authorize Attribute:
[Authorize(Roles="Administrators")]
public AcitonResult ManageUsers() {
return View();
}
Or
[Authorize(Users="Admin,SomeUser")]
public AcitonResult ManageUsers() {
return View();
}
More infos:
http://www.asp.net/learn/mvc/tutorial-17-vb.aspx
[Authorize(Roles = "Admin")]
public ActionResult ManageUsersController()
{
...
}
In your web.config check:
...
<forms loginUrl="~/your_login_page" defaultUrl="~/">
...
Also you should setup both MembershipProvider and RoleProvider in your web.config

Resources