【问题标题】:Form Authentication in MVCMVC 中的表单认证
【发布时间】:2018-10-19 19:34:48
【问题描述】:

我在 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 }

所以我在 Home 控制器的 Index Action 中给出了身份验证重定向,如下所示。

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

            //return View();
        }   
    }

但是,在通过身份验证后,我现在如何能够访问我的应用程序所需的 Controller 和 View?

【问题讨论】:

  • 如果我不得不猜测的话,看起来这就是 MyLogin.aspx url 中的 ReturnUrl 参数的用途。

标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-3 webforms


【解决方案1】:

使用默认网址。

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

【讨论】:

  • else部分是做什么的?
  • 重定向回强制登录重定向的请求资源。
  • 所以返回 Redirect(FormsAuthentication.LoginUrl);索引操作中不需要?抱歉,我没听懂。
  • 你能显示整个索引操作代码吗?喜欢重定向到身份验证登录页面,成功后转到我的控制器
  • 一般只需要重定向到登录或者登录后重定向。您的索引页面中的重定向将始终重定向到登录,即使用户经过身份验证,也不知道这是否是您想要的。由于您的表单处于活动状态,因此用户在未经身份验证时点击索引时将被重定向到您的登录名,但是,在登录/身份验证后,您需要将请求发送到某个地方。
猜你喜欢
  • 2014-12-28
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多