在我的ASP.NET MVC應用程序,我想弄清楚用戶是否有權訪問特定的控制器,由授權數據註解如下限制重寫OnAuthorization在基本控制器
[Authorize(Roles = "user")]
我試圖重寫OnAuthorization以檢查: -
- 如果請求被認證(偉大的工程)
- 如果用戶被授權訪問所請求的視圖(不工作)
我的用戶角色都存儲在我創建了一個SessionManager對象 - SessionManager.ActiveUser.Roles
下面是我在僞代碼的形式,但如果有人可以幫助我得到這個權利,我真的欣賞它。
public class HomeBaseController : Controller
{
protected override void OnAuthorization(AuthorizationContext context)
{
if (context.HttpContext.User.Identity.IsAuthenticated)
{
// these values combined are our roleName
bool isAuthorised = context.HttpContext.User.IsInRole(context.RequestContext.HttpContext.User.Identity.);
if (!context.HttpContext.User.IsInRole(---the roles associated with the requested controller action (e.g. user)---))
{
var url = new UrlHelper(context.RequestContext);
var logonUrl = url.Action("LogOn", "SSO", new { reason = "youAreAuthorisedButNotAllowedToViewThisPage" });
context.Result = new RedirectResult(logonUrl);
return;
}
}
}