2013-07-08 149 views
2

我使用授權屬性來檢查用戶是否被授權或不要進入特殊視圖。使用授權屬性ASP.Net MVC

[HttpGet] 
    [Authorize] 
    public ActionResult Index(int ID) 
    { 
      ViewBag.sID = ID; 
      return View(); 
    } 

假設這是畝URL:本地主機:16621 /面板/索引/ 1 現在,這個授權用戶可以更改爲1〜2,然後導航到另一個用戶的信息。像本地主機:16621 /面板/索引/ 2 如何防止這種?有沒有辦法將參數傳遞給授權屬性? 如何防止用戶訪問其他用戶信息?

+2

安吉麗娜。這已經是很多時間了。 http://stackoverflow.com/questions/2329197/custom-form-authentication-authorization-scheme-in-asp-net-mvc?rq=1 http://stackoverflow.com/questions/427598/customizing-authorization- in-asp-net-mvc?rq = 1 http://stackoverflow.com/questions/554094/asp-net-mvc-adding-to-the-authorize-attribute?rq=1 –

+0

看看這篇文章,它正是你想要的。 http://stackoverflow.com/questions/10064631/mvc-3-access-for-specific-user-only – SOfanatic

回答

4

恐怕沒有神奇的開關 - [授權]只是啓動未經授權的用戶,不在指定範圍內的用戶或錯誤角色的用戶。上下文綁定數據的安全性取決於您 - 您必須在Index()主體內部執行此操作,並在其他地方將用戶重定向,如果傳入的ID不適用於實際用戶。

+2

這不是一個好的解決方案。最好使用自定義的授權屬性。 – ataravati

1

有一個「AuthenticationFilter」ASP.NET MVC5可用於此目的。

Authentication filters

認證過濾器是一種新型的ASP.NET MVC過濾器,在ASP.NET MVC管道之前,授權過濾器 運行和 讓你的每次動作指定認證邏輯的,每個控制器, 或全局控制器。認證過濾器在請求中處理 憑證並提供相應的委託人。 身份驗證過濾器還可以在對未經授權的請求作出響應時在 中添加身份驗證質詢。

this tutorial如何使用它。

using System.Web.Mvc; 
using System.Web.Mvc.Filters; 

namespace VSMMvc5AuthFilterDemo.CustomAttributes 
{ 
    public class BasicAuthAttribute : ActionFilterAttribute, IAuthenticationFilter 
    { 
    public void OnAuthentication(AuthenticationContext filterContext) 
    { 
    } 

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) 
    { 
     var user = filterContext.HttpContext.User; 
     if (user == null || !user.Identity.IsAuthenticated) 
     { 
     filterContext.Result = new HttpUnauthorizedResult(); 
     } 
    } 
    } 
}