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

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.

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.

MVC FormsAuthentication time out - AJAX considerations

Hope you can help. In my ASP.net MVC3 app, all my controllers descend from a customized controller I have created.
Upon FormsAuthentication time out, my app correctly redirects users to the login page if they attempt to access any page (standard functionality).
However, for Ajax.ActionLink and Ajax.BeginForm calls, they just return nothing, which confuses users if the browser is left open for more than 20 minutes and then they try to access an Ajax link.
Is there any code I can put in to my base controller that will work generically so that when it detects an inbound Ajax call and we have timed-out, it will redirect users to my login page as expected?
I don't mind if it doesn't return to the original page afterwards - happy for it to just go to the Home Index page.
Thanks in advance for any help you can provide.
Simon.
You may take a look at the following blog post which illustrates a nice way to prevent the FormsAuthentication module from redirecting to the logon page in case of an AJAX request and simply send a 401 status code to the client so that it can act accordingly.

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. =)

How do you generate a AntiForgeryToken in a code behind file?

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.

AJAX timeout issue in MVC

I have an ASP.Net MVC application. I am using an AJAX request on a page which requires user authentication to fire an action on another controller, which returns a view to update a table on the page. The action that the AJAX request makes also requires authentication. The issue comes up when the user lets their session timeout and then does something to fire the AJAX request. The entire page does not redirect to the login page. Instead, the view returned to the AJAX request is the login page, which then is populated inside the div meant for the refreshed data table.
Is there a way to at least have the request return an error message instead of the login view?
Sure, you could create your own Authorize attribute and check if HttpContext.Current.Request.Headers["XMLHttpRequest"] then return error message else redirect to login page

Resources