2013-11-21 66 views
4

我是ASP.net MVC的新手,並使用它創建了我的第一個Web應用程序。在我的應用程序中,我使用數據庫身份驗我在控制器中創建了登錄操作,該操作會檢查輸入的用戶名和密碼是否存在於數據庫中,如果存在,則在Session中放入所需的值,並根據用戶的權限將用戶重定向到頁面,否則將用戶重定向到登錄頁面。像這樣如何在ASP.net中限制對控制器中某些操作的訪問MVC

public ActionResult Login() 
{ 
    if(uservalid) 
    { 
     //set session values and redirect to dashboard 
    } 
    else 
    { 
     //redirect to login 
    } 
} 

在我的應用程序中有一些功能只能在用戶登錄時訪問。我想在用戶試圖訪問這些功能之前檢查用戶是否登錄,如果他沒有登錄或沒有權限,則重定向到登錄頁面或顯示一些錯誤消息。

public ActionResult SomeAction() 
{ 
    //Available only when user is logged-in 
} 

那麼如何檢查用戶是否登錄並授予訪問權限。我閱讀了有關授權屬性,但不知道如何使用它,因爲我正在使用數據庫驗證。

回答

3

如果你正在使用FormsAuthentication你不需要使用ASP.NET會話跟蹤當前已驗證用戶。

我閱讀了關於授權屬性,但不知道如何使用它,因爲我是 使用數據庫驗證。

假設你去與FormsAuthentication,一旦你確認你應該設置窗體身份驗證cookie的用戶的憑據:

public ActionResult Login() 
{ 
    if(uservalid) 
    { 
     FormsAuthentication.SetAuthCookie("username", false); 
     return RedirectToAction("SomeProtectedAction"); 
    } 
    else 
    { 
     //redirect to login 
    } 
} 

然後:

[Authorize] 
public ActionResult SomeAction() 
{ 
    string currentlyLoggedInUser = User.Identity.Name; 
} 

通過萬一途中您可以在Visual Studio中使用Internet模板創建一個新的ASP.NET MVC應用程序,您可以查看AccountController,它負責驗證用戶身份並設置表單身份驗證Cookie。當然你可以拋棄所有的Entity Framework,並根據自己的數據庫表實現自己的憑據驗證。

3

我申請[Authorize]以及我自己的customattribute限制基於權限的行動。代碼如下

[Authorize] 
[FeatureAuthentication(AllowFeature=FeatureConst.ShowDashboard)] 
public ActionResult Index() 
    { 

    } 

過濾代碼

public class FeatureAuthenticationAttribute : FilterAttribute, IAuthorizationFilter 
{ 
    public FeatureConst AllowFeature { get; set; } 

    public void OnAuthorization(AuthorizationContext filterContext) 
    { 
     //var featureConst = (FeatureConst)filterContext.RouteData.Values["AllowFeature"]; 

     var filterAttribute = filterContext.ActionDescriptor.GetFilterAttributes(true) 
           .Where(a => a.GetType() == typeof(FeatureAuthenticationAttribute)); 
     if (filterAttribute != null) 
     { 
      foreach (FeatureAuthenticationAttribute attr in filterAttribute) 
      { 
       AllowFeature = attr.AllowFeature; 
      } 

      User currentLoggedInUser = (User)filterContext.HttpContext.Session["CurrentUser"]; 
      bool allowed = ACLAccessHelper.IsAccessible(AllowFeature.ToString(), currentLoggedInUser); 
      // do your logic... 
      if (!allowed) 
      { 
       string unAuthorizedUrl = new UrlHelper(filterContext.RequestContext).RouteUrl(new { controller = "home", action = "UnAuthorized" }); 
       filterContext.HttpContext.Response.Redirect(unAuthorizedUrl); 
      } 
     } 
    } 
} 
2

你應該創建一個basecontroller和繼承的基礎控制器等controlers然後檢查會話是否爲空或不對用戶進行身份驗證。

public class BaseController : Controller 
{ 
     protected override void OnActionExecuting(ActionExecutingContext filterContext) 
     { 
      if (Session["User"]== null) 
      { 
       filterContext.HttpContext.Response.Redirect("/somepage"); 
     } 

} 

public class SomeController : BaseController 
{ 

} 
相關問題