MVC Logoff browser history - asp.net-mvc

I´ve a .net 4.5 app with MVC 4 + WebAPI, and I'm facing a situation that I don´t know how to explain/solve.
My Logoff code is as follows:
public ActionResult SignOut()
{
FormsAuthentication.SignOut();
return Redirect("~");
}
This works, somehow, as expected (didn't verified for hacking scenarios).
However, if I do the following:
public ActionResult SignOut() {
{
FormsAuthentication.SignOut();
return Redirect("~/?logout=true");
}
It seems to still work, however, if the user hits the back navigation button on chrome (or backspace), he gets back to the login page!
Why is that happening?
Is there any other way to pass a parameter to the Redirect call?

Can you confirm that the page you are seeing is not the cache version? Press Shift-F5 and see if the page refreshes or if you are redirected to the login page instead. If that is the case, you can play with the cache settings to make sure users cannot go back to the page.

Related

Programmatically redirect unauthorized users using Microsoft.Owin.Security.OpenIdConnect

When I first started developing my MVC app (which requires authorization, to selectively render a SPA, which in turn does it's own authorization via ADAL.js) I simply decorated the HomeController's Index method with [Authorize] like thus,
[Authorize]
public ActionResult Index(bool ok = false)
{
return View();
}
and everything works fine.
However, sometimes I want users to share URLs with each other. My SPA uses hash-based routing to render various states. As long as both users are logged in already, they can share links with each other and everything magically works ok.
But, if the user clicking a link is yet-to-login, we lose the state communicated in the URL.. everything after the hash.. e.g. if user A sends unauthenticated user B this URL: http://mycorp.com/#/orders/85/edit the HomeController's going to notice user B is unauthenticated, and the middleware is going to kick user B over to our Microsoft login page.. and when he redirects back, the critical #/orders/85/edit portion of the URL in is gone.
My solution was to remove the [Authorize] attribute from the Index action, and instead do something like this:
public ActionResult Index(bool ok=false)
{
if (!User.Identity.IsAuthenticated)
{
if (!ok)
return View("SetCookie_Then_RedirectWith_OK_InQueryString");
if (ok)
//how do I do this part?
return new RedirectResult(Microsoft.Owin.Security.OpenIdConnect.Url);
}
else
//now we're authenticated,
//let JS resume by looking for cookie set previously
return View("Index");
}
Notice the how do I do this part comment above. That's my question.
+++++++++ FWIW ++++++++++
My app features a Startup.Auth.cs file with the familiar middleware declared...
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
...blah...
}
);
I presume I can do something fancy here in Startup.Auth.cs w/Notification Handlers but, I was hoping to directly call the middleware into action from the Index method.

FormsAuthentication.RedirectToLoginPage() vs RedirectToAction("Login", "Account")

I am using Forms Authentication in my website. I have seen in some example code that one can call .SignOut() and then use
FormsAuthentication.RedirectToLoginPage()
to send a user to the login page.
What advantage, if any, does this have over calling
RedirectToAction("Login", "Account");
in an MVC website? From MSDN it seems that the former will not call HttpResponse.End() which means that code that follows will execute... I'm not sure when I would need to use this feature.
FormsAuthentication.RedirectToLoginPage() does have some advantage where it will attempt to append ?ReturnUrl={url} to the login page URL which can be used later to return the user to the page they were requesting when the login redirect happened. Using this method uses Response.Redirect() which goes against the MVC mentality. You'll lose out on events like OnActionExecuting from firing in your controller/filters. source code of RedirectToLoginPage
RedirectToAction("Login", "Account"); doesn't have the ReturnUrl feature out of the box, but it does keep everything in the MVC ecosystem so the events fire. In the case if logging someone out and redirecting back to the login page, I'd probably keep it all in MVC and use RedirectToAction. Or potentially use Redirect(FormsAuthentication.Url); if you always want to use the login page URL from the web.config.
Do a SignOut(), but then return a HttpUnauthorizedResult so that the controller will just use it's regular login redirect.
If you are signing out in your OnActionExecuting controller event, do it this way...
protected override void OnActionExecuting(ActionExecutingContext filterContext) {
if (//I need to log out...) {
System.Web.Security.FormsAuthentication.SignOut();
filterContext.Result=new System.Web.Mvc.HttpUnauthorizedResult();
return;
}
base.OnActionExecuting(filterContext);
}

My ASP.NET MVC app takes me back to the login page when I access the home controller even though I'm logged in

When I log in as a user, and type the url http://localhost:50562/Home/Index into the address bar, the browser takes me to the login page, which is my home page, but the funny thing is that the message "welcome, user!" and Logout link are still there in the upper right corner. When I click on the other links in the nav bar, the session continues normally, meaning, I was never logged out.
Can someone tell me how to configure the routing engine to take me to another page when I access the Home controller while being logged in?
You can achieve this by modifying the POST method for Login in the Account Controller (assuming you are using MVC 4 and the Simple Membership it uses).
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
...
}
You can set the routing in a few ways.
return RedirectToAction("Profile", "Home"); ... where Profile is a Controller
return View(returnUrl); ... where you have set and assigned the variable in your method
or retain as above with RedirectToLocal(returnUrl);
Good luck.
What you're describing happens because the user cookie isn't read until after the redirect to the home page is initiated. The best way to initialize your membership provider when users may enter on different pages is to use a global filter.
You can add this functionality for the SimpleMembership provider in the RegisterGlobalFilters method in the FilterConfig class in the App_Start folder
filters.Add(new YourAppNameSpace.Filters.InitializeSimpleMembershipAttribute());
Using a filter keeps you from having to repeat yourself with decorators all over your controller classes. It's easy to overlook adding decorators and, when they aren't there, your site will have unexpected bugs.
Thank you for your answers, but it seems that the project had a SessionObject class all along, which was handled by the controller. I am not the original author of the project, so it took me a while to figure it out. I was tasked to give it some additional features and bugfixes.
I ran into the method:
#region getSessionObject()
protected SessionObject getSessionObject() {
SessionObject loReturnValue = null;
if (Session[SessionObject.SESSION_CONSTANT] != null)
loReturnValue = (SessionObject) Session[SessionObject.SESSION_CONSTANT];
return loReturnValue;
}
It was all I needed to call in the index action of my home controller to check whether the user is logged in or not.

Best way to implement form in Layout page in ASP.Net MVC 3 project

My site has a login box in the Layout page on which every page is based. When the Login button is clicked, no matter it is successful or failure, the user will be sent to the same page where the Login button is clicked.
The login form is posted to Account.Login action method. However, how can I return the correct view at the end of this action method? I also want to show error information beside the login box ie: wrong username/password in the case of failure to login.
What's the best way to design and implement this?
[HttpPost]
public ActionResult Login(LoginModel model)
{
if(ModelState.IsValid)
{
//TODO : Log user in
return View("ValidModelView");
}
// If login model is not valid
return View("InvalidModelView");
}
One approach might be this. However, I am not sure whether it is the best one.
Just do a Redirect on successful login.
return RedirectToAction("Index", "Home");

Logout in MVC using Session without JavaScript/JQuery

Hi I'm relatively new to MVC 3 and I'm working with logging out my application, I managed to do the logging in, staying logged in even if website is opened on another tab.
All of my views (except for the home, of course) has this:
Logout
and in my controller I have this:
public ViewResult Logout()
{
Session.Abandon();
return View("Index", "Home");
}
and the app is not logging out, instead it is returning the current view.
Please help me understand what to do, and I would like to take note that I am using ViewResult instead of ActionResult, I'm not also going to use JavaScript or JQuery, because I'm making this app to show how MVC works.
Shouldn't you be pointing to the logout action?
Logout
Assuming the path to you're logout action is \Home\Logout
UPDATE:
Another old fashioned way is..
Upon successful login..
Session["Login"] = true; //or any object that describes the user's identity
On every page you need to check
var login = Session["Login"];
if(Convert.ToBoolean(login)){ //or cast to your expected object
//do something
}
else{
//redirect to logout/login page
}
Upon logout,
Session["Login"] = null;
If you are using forms authentication you should also clear the authentication cookie and redirect after logging out:
public ActionResult Logout()
{
Session.Abandon();
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}

Resources