How do you generate a AntiForgeryToken in a code behind file? - asp.net-mvc

I have an action that resets a user's password. In that same action after the password is reset I want to login the user. I wanted to just use a "RedirectToAction" and send the username and password to my SignIn action. Since I have logic in that action that handles errors and what not.
So I need to send the AntiForgeryToken value to the SignIn action also.

The AntiForgeryToken is only valid for POST requests (GET requests are supposed to be idempotent... that is, not change state on the server). RedirectToAction does an HTTP/302 redirect, which is results in a GET request. Therefor, an AntiForgeryToken would make no sense for RedirectToAction.
I would reconsider what it is you are trying to do.
Remember, actions are just public methods on the controller, so you should be able to call one (and return its result) from any other action.

There isn't a need to do this and I don't think it would be a good idea anyway as you'd be passing the password back to the browser as part of the response. Just use FormsAuthentication to create the auth cookie and send it back with the response.

Related

Spring security authentication - looks like infinity loop but it works. How?

how does it really works?
I wrote a sample app using spring boot with security and thymeleaf.
As [tutorial]: http://www.thymeleaf.org/doc/articles/springsecurity.html shows ones just need to create controller and login page. But...
In security config there is fragment as
loginPage("/login.html")
then in controller there is request mapping for /login like
#RequestMapping("/login.html")
public String login() {
return "login.html";
}
and then in thymeleaf page there is action mapping like
<form th:action="#{/login.html}" method="post">
So..when ones try to access restricted page is redirected to login page which means that login.html is displayed. Then after filling the form user clicks the button and trigger action which is mapped on controller that returns login.html once again. Looks like a loop. But it works. How??
I think I see the confusion here. In recent versions of Spring Security, it is possible and even encouraged by default that the login page and login processing URL are the same address (but they don't need to be). This is possible because of different HTTP methods.
When redirected to login page, the page is retrieved using a GET request. The authentication filter sees this, but passes on the request to Spring MVC and the controller, since it is a GET request.
When submitting the form, the username and password are sent in a POST request. The authentication filter intercepts this request since it is POST, performs the authentication and takes action depending on the result. The request is not forwarded to the controller in this case.

In ASP MVC, how should I structure my controler for a registration process with confirmation page

I am still new to ASP MVC 4 and I need some help to design my controler for a basic registration scenario with a confirmation page.
I have a form where the user enters some personal information, with some model validation using validation attributes. On the submit of this form, I need to call my datalayer for more complex validations before redirecting to a confirmation that shows to the user's input so that he can verify everything. So it is only on the submit of this confirmation form that the create action happens in the database.
I read about the PRG pattern (Post-redirect-Get) and I am a bit confused because I do not want any of the personal data to appear in the URL between the registration and the confirmation form.
I hope I am clear enough in the explation of my situation..
This is a pretty basic scenario that we see pretty much everywhere so I hoped to find exmaples somewhere but I can't find any article or tutorial about it.
Thanks in advance!
Well I would build the controller class as shown below .. I will be using session to store the user information to get it to the confirmation page, but you can choose any other ways maybe like a cookie if that is okay from a security perspective
Public class RegistrationController:Controller
{
[HttpGet]
public FillInformation()
{
...
Return view();
}
[HttpPost]
public FillInformation(UserInformation UserInformation)
{
if (ModelState.IsValid)
{
//do some further validation here and if succeed then save to session
Session["info"] = UserInformation;
return RedirectToAction("Confirmation");
}
Return view(UserInformation);
}
[HttpGet]
public Confirmation()
{
// get object from session
UserInformation info = Session["info"]
Return view(info);
}
[HttpPost]
public Confirmation()
{
// get object from session
UserInformation info = Session["info"]
//Save data to database here
}
}
Also since you are using MVC 4, another way to do this would be using a service call by implementing a WEB API service.
You can use this pattern. Although the name is Post Get Redirect, the first time the user will do a GET of the login page, by typing it in his browser. The server will send an empty form as an answer. Once the user has the form on his browser, you are on the POST step of PRG:
POST: the user fills the form, and submits it (when the client side validation is succesful). When the server gets the data, it can make a server side validation. If the server side validation fails, the server sends the form back to the user, so that he can try again. The server and user will exchange the form several times, until the server validation is ok.
REDIRECT: Once the server side validation is ok, the server registers the user and sends a redirect (HTTP 301 or 302) to the browser, which includes the new URL that the browser must load.
GET: when the browser receives the Redirect from the server, it issues a GET of the new URL.
The redirect url will usually show a next step, or a confirmation page. In this case it could be a "Registration Succesful" page.
The advantage of the PRG pattern is that refreshing the browser (reloading the page) will not have undesired side effects (like registering the user twice in this sample):
if the users refresh the browser in the POST step, the form is sent back to the server. But the user can only do this while he is in the POST step (and thus, is not still registered)
once the user is registered, the browser has been redirected to a new page, using GET. So, if the user refreshes the browser he repeats the GET, and nothing happens on the server side.
I.e, if you correctly implement this pattern, the server shuld only make actions (like registering the user) on POST requests. In the GET requests the application should only show data to the user, but make no changes.
By the way, all the personal data will be posted in the first step (POST) to the server. The URL used in the REDIRECT and GET steps doesn't have any personal information url. To do this, you'll normally store the neccessary personal data in session, once the user is registered / authenticated.
You can store the user data in the session after the validation by the server. Then display everything on the confirm page for the user. And finally store everything in the database.
One other possibility is to store it in TempData. It is basically a session variable that only last until the next request. However that means that if on a page refresh the data is lost.

asp.net mvc 2 -- losing authorization when RedirectToAction with JSON data

I'm refactoring some MVC code that originally used POST'ed form data. The form's fields are serialized using jquery's serialize() method and sent to an MVC controller Save Action that checks things out and redirects as appropriate (if errors in form values, redirect to the Edit Action, if fine then save and redirect to the Display Action). All actions are invoked via AJAX and return Partial Views. Everything works grand. Note: The site uses AD-based authorization, so users are prompted for their windows credentials upon first loading the site, but are never prompted again.
However, I'm now looking to interact with the server via JSON objects instead of form fields. Granted, I serialize the JSON object on the client and, with the aid of an imported MVC2 Futures/MVC3 class JsonValueProviderFactory, am able to correctly model bind the sent JSON object to a C# class in the Controller's parameters.
I maintain the same logic, but things start to blow up when I try to return a RedirectToAction ActionResult when the Controller accepts JSON objects. I lose authentication, the user is prompted for their credentials again, and I find myself in a infinite loop on the originally requested Action (save). Every time the user is prompted for credentials and simply runs through the Save Action again. The end result for the user is an unending alerts prompting for login credentials. Neither of the actions specified in the RedirectToAction calls are ever hit.
Can the fact that the original request uses a JSON contentType be interfering with the behavior of RedirectToAction? That's the only thing I can think of as it works fine when I don't use JSON to post and it works fine when I return PartialViews instead of using RedirectToAction. The infinite repeat of the Controller Action and continual loss of authorization credentials seems to suggest that RedirectToAction is not the way to go in this situation.
I can post code on request. I am also successfully handling stuff like copying the ModelState over to TempData and other RedirectToAction tricks. Again, it DOES work when using a non-JSON solution. Any insight is greatly appreciated!!
EDIT WITH FOLLOW-UP INFO:
Turns out, I get an "Unauthorized" error even when I completely disable NTLM authentication/authorization for the site. IIS server doesn't look for any authorization, web site doesn't look for any authorization, yet the error when trying to Redirect with JSON contentType request still occurs and complains of being "Unauthorized". This is WEIRD.
To update everyone, I haven't found a solution nor do I know for-sure what the situation is. However, I'm willing to bet it has to do with the fact that RedirectToAction issues http GET requests and the action I'm redirecting to only accepts POSTs. Even if I remove the restriction, it's still sending JSON data and it still needs to be done by POST.
In short, RedirectToAction with JSON data appears to be fundamentally undoable. You need to POST JSON data but RedirectToAction emits GET requests. That's my going theory, at least. =)

What is the best way to expire client session?

In my asp.net mvc where to put code to expire browser session when server session expires. Can I use any action attribute? Which should be the best?
EDIT
Based on your comment, I would suggest handling this via a custom base controller that all of your other controllers would derive from. Have the custom base controller override OnActionExecuting and check for an expired state. If the state is expired, remove the authentication cookie from the response (FormsAuthentication.SignOut) and set the Result property on the ActionExecutingContext parameter to HttpUnauthorizedResult. Alternatively, you could simply redirect to a Logout action.
You should also make sure that your session timeout and the forms authentication cookie timeout are the same.
Original answer left for context
I'm not sure exactly what you're asking. When the server session expires, the authentication ticket in the cookie is no longer valid. Any action that requires authorization (which minimally requires authentication) should get back an HttpUnauthorizedResult, which by default redirects to the Forms logon page.
Are you asking how to expire the session on the client-side so that the client does something even in the absence of a request? If so, you might be interested in how I handle this via javascript/ajax. See my blog post on client-side session termination at http://farm-fresh-code.blogspot.com.
I think you want to clear browser history after user sign out.

Rerouting back to the previous controller and action in mvc.net

I have a UserController that have methods like Register, Login, Logout, etc.
On my site I have a small login form that i've made as a partial view and is part of a masterpage. The behaviour I want is to be able to login from any view and then return to the controller I was at when i called the Login method.
I can call the methods from anywhere just fine, but can't figure out what to do to find out what controller and action the user was at to reroute back.
Use the Referer header from the HTTP Request. In PHP you get it with $_SERVER['HTTP_REFERER']; I don't know how it's done in ASP.NET, but it shouldn't be too hard if you google for "HTTP Header Referer".
Referer is not guaranteed to be populated, since some proxies do not send it. So I would recommend against depending on it.
Instead, when you redirect a user from a protected page to login page, save where they were into the Session object, or Viewdata, or maybe TempData object. So you can use the value in there to redirect them back to where they were when they successfully log in.

Resources