簡體   English   中英

如何限制對MVC5中某些操作的訪問?

[英]How do I restrict access to some actions in MVC5?

我正在開發一個ASP.NET MVC5項目,使用MySQL(實際上更像MariaDB)作為數據庫和EF6。我決定使用“本機”身份驗證方法,因為它使用了SQL Server,所以...很好。 我需要解決一些問題。

假設有一個名為“ Persons”的控制器,帶有默認的EF CRUDE。 問題是,我希望默認的登錄用戶訪問“詳細信息”和“列表視圖”,而不是“創建”,“刪除”和“編輯”視圖。 因此,根據SO中的一些答案,我想出了“解決方案”:

創建一個繼承Controller類的抽象類,並在OnActionExecuting處定義一個重寫方法:

public abstract class InternalAreaBaseController: Controller {
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        if ( Session["UserObj"] == null ) {
            Response.Redirect( @"~\AcessoNegado\Desconectado" );
        }
        else{
            base.OnActionExecuting( filterContext );
        }

    }
}

我做了public class PersonsController : InternalAreaBaseController所需的繼承,並且它可以正常工作:如果當前會話不包含“ UserObj”對象(該對象基本上檢測到用戶是否已連接),則重定向到“ Disconnected”錯誤頁面。

但是,這僅檢查用戶是否已連接。 PersonsController內部,有所有用戶都可以訪問的動作public ActionResult Index() ,但也有只能由用戶在確定的條件下訪問的動作public ActionResult Create()

有沒有一種方法可以在PersonController:InternalAreaBaseController旁邊傳遞標志,以便抽象類知道何時阻止確定的用戶?

就像是

public abstract class InternalAreaBaseController: Controller {
public int AccessDegree { get;  set; }
public User? SessionData = Session["UserObj"];
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{

       if ( SessionData == null ) {
           Response.Redirect( @"~\AcessoNegado\Desconectado" );
       }
       elseif(SessionData.AccessDegree<AccessDegree){
            Response.Redirect( @"~\AcessoNegado\SemCredenciais" ); //NotEnoughCredentials
       }
       else{
           base.OnActionExecuting( filterContext );
       }

    }
}

您可以使用這種方式。

public ActionResult Login()
{
   bool IsValidUser = // Check User Credential
   if(IsValidUser) // If it is valid
   {
      FormsAuthentication.SetAuthCookie("username", false);
      return RedirectToAction("Index");
   }
   else
   {
      //Show the message "Invalid username or password"
   }

}

在控制器中

[Authorize]
public ActionResult Index()
{
   // Do something
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM