Аутентификация формы в MVC - PullRequest
0 голосов
/ 09 мая 2018

У меня есть форма аутентификации в приложении MVC. Страница входа размещается по указанному ниже адресу Код:

 <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>

Мой App_Start имеет следующий файл RouteConfig

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

Итак, я дал перенаправление аутентификации в Index Action of Home контроллер, как показано ниже.

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return Redirect(FormsAuthentication.LoginUrl);

            //return View();
        }   
    }

Но как теперь я смогу перейти к своим приложениям, требуемым Controller и View после того, как он будет аутентифицирован?

1 Ответ

0 голосов
/ 09 мая 2018

Использовать URL по умолчанию.

<forms loginUrl="~/Account/Login" defaultUrl="~/Home/Index"/>

А затем используйте перенаправление после аутентификации, подобное:

//Request is authenticated go to some url
HttpContext.Current.Response.Redirect(FormsAuthentication.DefaultUrl);

Или

//Request is authenticated go to the page that caused the 302 redirect
FormsAuthentication.RedirectFromLoginPage(myTicket.UserName,createPersisentToken);

В вашем контроллере MVC это будет выглядеть примерно так.

[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);    
    } 
}
...