【问题标题】:How to stop authorization loop?如何停止授权循环?
【发布时间】:2014-02-04 18:32:25
【问题描述】:

当我进入我的主页时,[Authorize] 标签会将我重定向到登录页面(很好!)。但是在我输入凭据后,它似乎只是刷新了登录页面(糟糕!)。

家庭控制器:

[Authorize]
public class HomeController : Controller
{
    public  ActionResult Index()
    {
        return View();
    }
    //other code
}

账户管理员:

[Authorize]
public class AccountController : Controller
{
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel loginModel, string returnUrl)
    {
        UserRoles userRoles = new UserRoles();
        UserRole userRole = userRoles.DbSet.FirstOrDefault(u => u.User == loginModel.UserName);

            if (ModelState.IsValid && Membership.ValidateUser(loginModel.UserName, loginModel.Password))
            {
                return RedirectToLocal(returnUrl);
            }

            ModelState.AddModelError("", "Bad login");            

           return View(loginModel);
    }
    //other code
}

编辑 1:

loginModel 在我填写登录表单后自动传入。

returnUrl是之前访问过的url,在本例中,就是home controller。默认情况下,它也是家庭控制器。

我认为问题可能是由于未将用户设置为已通过身份验证,因此当它返回主控制器时,[Authorize] 标记再次激活。大家觉得呢?

编辑 2: 在 Global.asax.cs 中:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

这里没有自定义路由表,一切都是默认的。

在 Web.Config 中:

<authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

正确连接到我的登录功能。

会员认证有效,我已经测试过了。

【问题讨论】:

    标签: c# asp.net-mvc authentication membership-provider


    【解决方案1】:

    试试这个:

    if (ModelState.IsValid && Membership.ValidateUser(loginModel.UserName, loginModel.Password))
    {
        FormsAuthentication.SetAuthCookie(loginModel.UserName, true);
        return RedirectToLocal(returnUrl);
    }
    

    【讨论】:

    • 天啊!完全把我的饼干忘在烤箱里了!非常感谢!
    猜你喜欢
    • 2018-05-13
    • 1970-01-01
    • 2019-09-01
    • 2022-01-11
    • 2014-05-30
    • 2010-09-26
    • 2012-06-19
    • 2019-07-01
    • 2013-09-11
    相关资源
    最近更新 更多