2013-07-10 63 views
4

我有一個產品控制器「product_editor」所需的角色來訪問大多數方法。有一些操作不需要授權,因此[AllowAnonymous]很好。但是,我有一個操作,我想要求他們已登錄,但他們可能不是產品編輯器。在控制器中授權一個動作,但不需要角色

是否有一種簡單的方法來聲明一個動作?

你可以看到一對夫婦我嘗試註釋掉

[Authorize(Roles = "product_editor")] 
public class ProductController : Controller 
{ 
    #region Public Actions 
    [AllowAnonymous] 
    public ActionResult Search(string keyword... 

    [AllowAnonymous] 
    public ActionResult Details(string id... 
    #endregion 

    //[Authorize] 
    //[Authorize(Roles="")] 
    public ActionResult AuthorizedDownload(long id, string step) 
    { 
     SecureDownloadLink link = SecureDownloadLink.Load(id); 
     if(link.belongsTo(HttpContext.Current.User.Identity.Name)) 
     { 
      //Allow download 
     } 
     else 
     { 
      //Return 404 Error 
     } 
    } 
} 

- 編輯 -

找到一個可行的解決方案,但由於我的身份驗證的其餘部分完成很想基於屬性的解決方案屬性和[AllowAnonymous]有點誤導。

[AllowAnonymous] 
public ActionResult AuthorizedDownload(long id, string step) 
{ 
    if (!User.Identity.IsAuthenticated) 
     return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.LocalPath }); 
.... 
} 

回答

4

我不認爲有一個簡單的方法來實現這一目標,除了明確指定授權上的每個控制器動作明確屬性:

public class ProductController : Controller 
{ 
    #region Public Actions 
    [AllowAnonymous] 
    public ActionResult Search(string keyword... 

    [AllowAnonymous] 
    public ActionResult Details(string id... 
    #endregion 

    [Authorize] 
    public ActionResult AuthorizedDownload(long id, string step) 
    { 
     SecureDownloadLink link = SecureDownloadLink.Load(id); 
     if(link.belongsTo(HttpContext.Current.User.Identity.Name)) 
     { 
      //Allow download 
     } 
     else 
     { 
      //Return 404 Error 
     } 
    } 

    [Authorize(Roles = "product_editor")] 
    public ActionResult SomeOtherAction() 
    { 
     ... 
    } 
} 

,或者如果你有很多的行動,另一種可能是在單獨的控制器中移動不同的動作。

0

授權使用級聯規則,所以您稍微簡化了它。

[Authorize] 
public class ProductController : Controller 
{ 
    #region Public Actions 
    [AllowAnonymous] 
    public ActionResult Search(string keyword... 

    [AllowAnonymous] 
    public ActionResult Details(string id... 
    #endregion 

    public ActionResult AuthorizedDownload(long id, string step) 
    { 
     SecureDownloadLink link = SecureDownloadLink.Load(id); 
     if(link.belongsTo(HttpContext.Current.User.Identity.Name)) 
     { 
      //Allow download 
     } 
     else 
     { 
      //Return 404 Error 
     } 
    } 

    [Authorize(Roles = "product_editor")] 
    public ActionResult SomeOtherAction() 
    { 
     ... 
    } 
} 
相關問題