在我的ASP.NET MVC应用程序中,我试图弄清楚用户是否可以访问特定控制器,受授权数据注释的限制如下
[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;
}
}
}
答案 0 :(得分:10)
根据ProASP.NET MVC3 Book重写OnAuthorization,他们不建议覆盖它,因为此方法的默认实现安全地处理使用OutputCache Filter缓存的内容。
如果您正在寻找自定义身份验证(使用Forms Auth)和授权(使用角色提供程序逻辑,那么以下是我保护应用程序的方式。
编辑:以下逻辑使用内置表单身份验证和角色管理器。用户通过身份验证和授权后,可以使用用户身份检查身份验证(User.Identity.IsAuthenticated)和角色User.IsInRole(" admin")
在Web.Config中:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="15" slidingExpiration="true" enableCrossAppRedirects="false" protection="All" />
</authentication>
<roleManager enabled="true" defaultProvider="MyRolesProvider" cacheRolesInCookie="true" cookieProtection="All">
<providers>
<clear />
<add name="MyRolesProvider" type="MyApp.Library.CustomRolesProvider" />
</providers>
</roleManager>
对于角色授权,根据需要扩展RoleProvider并覆盖方法。
public class CustomRolesProvider : RoleProvider
{
public override string[] GetRolesForUser(string username)
{
// You need to return string of Roles Here which should match your role names which you plan to use.
//Some Logic to fetch roles after checking if User is Authenticated...
return new string[] { "admin" , "editor" };
}
//Rest all of them I have kept not implemented as I did not need them...
}
在你的控制器中现在你可以使用它:
[Authorize(Roles="Admin")]
public class AdminController : Controller
{
....
}
对于身份验证我已经实现了自定义身份验证检查,但我仍然使用表单身份验证:
//This one calls by Custom Authentication to validate username/password
public ActionResult LogOn(LogOnViewModel model, string returnUrl)
{
if(Authenticate("test","test"))
{
.......
}
}
public bool Authenticate(string username, string password)
{
//Authentication Logic and Set the cookie if correct else false.
//..... your logic....
//.....
FormsAuthentication.SetAuthCookie(username, false);
}