这是一个MVC3项目。只是为了测试,我有
public class MyRoleProvider : RoleProvider
{
public override string[] GetRolesForUser(string username)
{
return new string[] { "0", "1", "2", "4" };
}
public override bool IsUserInRole(string username, string roleName)
{
bool result = true;
return result;
}我在web.config中注册它。然后,如果我配置了标准的SqlMemberShipProvider,下面这样的代码将会触发我的GetRolesForUser。
[Authorize(Roles="4")]
public class AdminController : Controller
{ //...但是,我不想使用标准的SqlMemberShipProvider。我自己的AuthorizeAttribute定义如下,只是为了测试:
public class MyAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool result = true;
return result;
return base.AuthorizeCore(httpContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
}现在,下面的代码将不再导致MyRoleProvider.GetRolesForUser触发。
[MyAuthorize(Roles="4")]
public class AdminController : Controller
{ //...上面的代码会触发MyAuthorize.AuthorizeCore和MyAuthorize.OnAuthorization,但不会触发MyRoleProvider中的方法。MemberShipProvider、RoleProvider和AuthorizedAttribute之间的关系是什么?这些关系是什么时候定义或配置的?
谢谢。
发布于 2012-03-29 22:31:06
如果你不想使用标准的SqlRoleProvider,就不要配置它。我通常会将其注释掉或删除。
您的配置将如下所示:
<roleManager defaultProvider="MyRoleProvider" enabled="true">
<providers>
<clear />
<!--<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />-->
<add name="MyRoleProvider" type="Full.Namespace.Of.MyRoleProvider" applicationName="/" />
</providers>
</roleManager>发布于 2012-03-29 21:59:16
我不知道这是不是一个拼写错误,但是base.AuthorizeCore会检查角色中的用户,所以
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool result = true;
return result;
return base.AuthorizeCore(httpContext);
}返回总是true,并且不激发基方法。尝试删除
bool result = true;
return result;下面是MVC源代码中的一段代码
// This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.
protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
if (httpContext == null) {
throw new ArgumentNullException("httpContext");
}
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated) {
return false;
}
if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {
return false;
}
if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) {
return false;
}
return true;
}https://stackoverflow.com/questions/9926663
复制相似问题