Reputation: 67
I have a Form Authentication in MVC application. The login page is hosted in the below url. The code is :
<authentication mode="Forms">
<forms loginUrl="http://localhost:100/MyLogin.aspx?ReturnUrl=%2f" name="adCookie" protection="All" timeout="10" slidingExpiration="true" defaultUrl="~/Default.aspx" enableCrossAppRedirects="true" />
</authentication>
My App_Start has following RouteConfig file
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
So I gave the authentication redirect in Index Action of Home controller like below.
public class HomeController : Controller
{
public ActionResult Index()
{
return Redirect(FormsAuthentication.LoginUrl);
//return View();
}
}
But, how will I now be able to go to my applications required Controller and View after it is been authenticated?
Upvotes: 1
Views: 795
Reputation: 15185
Use the default url.
<forms loginUrl="~/Account/Login" defaultUrl="~/Home/Index"/>
And then use a redirect after authentication similar to :
//Request is authenticated go to some url
HttpContext.Current.Response.Redirect(FormsAuthentication.DefaultUrl);
Or
//Request is authenticated go to the page that caused the 302 redirect
FormsAuthentication.RedirectFromLoginPage(myTicket.UserName,createPersisentToken);
In your MVC controller, it would go something like this.
[Authorize]
public class HomeController : Controller
{
public ActionResult Index()
{
//The response will not hit here if not authenticated
//return Redirect(FormsAuthentication.LoginUrl);
return View();
}
}
[Authorize]
public class AccountController : Controller
{
public ActionResult Login(LoginModel model)
{
if(DoSomeLoginAndSetAuthenticationTicket())
FormsAuthentication.RedirectFromLoginPage(...);
return View(model);
}
}
Upvotes: 1