2015-10-20 177 views
-1

我刚开始尝试使用MVC,并注意到授权属性限制对已验证用户的访问。不幸的是,它现在似乎不工作。如何使用MVC Authorize属性?

下面是我的代码:

Web.config文件:

<authentication mode="Forms"> 
    <forms loginUrl="/Login/Index" timeout="30"/> 
</authentication> 

登录控制器:

[AllowAnonymous] 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    [HttpPost] 
    [AllowAnonymous] 
    public ActionResult ValidateLogin(UserLogin userLog) 
    { 

     if (userLog.UserName != "admin" || userLog.Password != "admin") 
     { 
      ModelState.AddModelError("Error Message", "Wrong Login Credentials."); 
      return View("Index", userLog); 
     } 

     return RedirectToAction("Index", "Home"); 
    } 

首页控制器:

[Authorize] 
    public ActionResult Index() 
    { 
     return View(); 
    } 

它仍然会阻止访问后进入一个 正确登录。

谢谢。

[HttpPost] 
[AllowAnonymous] 
public ActionResult ValidateLogin(UserLogin userLog) 
{ 
    if (userLog.UserName != "admin" || userLog.Password != "admin") 
    { 
     ModelState.AddModelError("Error Message", "Wrong Login Credentials."); 
     return View("Index", userLog); 
    } 

    // Signing in the user will make the Authorize attribute work! 
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager)); 

    return RedirectToAction("Index", "Home"); 
} 

备选

+2

那么你验证用户,但你实际上并没有登录 – DavidG

回答

1

尝试由的AuthenticationManager实际的登录扩展您的登录方法? 我有心脏有关FormsAuthentication,但到目前为止还没有使用过它,也许这是一个选项你,但AuthenticationManager非常易于使用!

登录:

FormsAuthentication.SetAuthCookie(username, false); 

注销:

FormsAuthentication.SignOut(); 
+0

您好,感谢。 我仍然不确定实际授权检查以允许访问? 有没有其他方式不使用AuthenticationManager,就像我们自己的自定义登录验证一样? 谢谢 – hollycrab

+0

也许你应该寻找一个自定义的授权属性呢? –

+0

嗨,所以为了验证MVC中的用户并使用Authorize属性,我们必须使用AuthenticationManager并且不能使用类似cookie的东西? 谢谢。 – hollycrab

相关问题