2015-10-20 171 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

相關問題