【问题标题】:SimpleMembership: AuthorizeAttribute and User.IsInRole not workingSimpleMembership:AuthorizeAttribute 和 User.IsInRole 不起作用
【发布时间】:2016-02-29 12:54:53
【问题描述】:

过去一周我一直在为此绞尽脑汁,但我在这里或其他地方找到的答案似乎都没有任何作用。我有一个使用 SimpleMembership 的 ASP.NET MVC5 应用程序。我有一个名为 OrganisationsController 的控制器,它具有以下属性:

[Authorize(Roles = "Administrator")]

我检查了数据库,我登录的用户确实是“管理员”角色。但是,Authorize 属性和 User.IsInRole() 都不会为该角色返回“true”。

Authorize attribute not working with roles建议

AuthorizeAttribute 调用存储在 HttpContext.User 中的 IPrincipal 实例的 IsInRole 方法。默认情况下,IPrincipal 没有角色,在这种情况下 IsInRole 将始终返回 false。这就是拒绝访问您的操作的原因。

我已按照该答案中的建议使用以下代码,但 authTicket.UserData 仍然为空。

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {
      FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
      string[] roles = authTicket.UserData.Split(',');
      GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
      Context.User = userPrincipal;
    }
}

我不知道出了什么问题。为什么我可以登录,但找不到任何角色?

以下是 web.config 的一些相关部分:

 <roleManager enabled="true" defaultProvider="SimpleRoleProvider">
      <providers>
        <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
      </providers>
    </roleManager>


    <membership defaultProvider="SimpleMembershipProvider">
      <providers>
        <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
      </providers>
    </membership>

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" cookieless="UseCookies" />
    </authentication>

这是我定义的 InitializeSimpleMembershipAttribute:

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
    private static SimpleMembershipInitializer _initializer;
    private static object _initializerLock = new object();
    private static bool _isInitialized;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Ensure ASP.NET Simple Membership is initialized only once per app start
        LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
    }

    private class SimpleMembershipInitializer
    {
        public SimpleMembershipInitializer()
        {
            Database.SetInitializer<UsersContext>(null);

            try
            {
                using (var context = new UsersContext())
                {
                    if (!context.Database.Exists())
                    {
                        // Create the SimpleMembership database without Entity Framework migration schema
                        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    }
                }

                if (!WebSecurity.Initialized)
                {
                    WebSecurity.InitializeDatabaseConnection("VerhaalLokaalDbContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
            }
        }
    }
}

InitializeSimpleMembershipAttribute 仅在 AccountController 上设置。

这里到底发生了什么?为什么找不到在数据库中定义并与用户绑定的角色?

【问题讨论】:

  • 似乎您自己回答了这个问题:“InitializeSimpleMembershipAttribute 仅在 AccountController 上设置”。您正在向 OrganizationController 请求某些内容,因此 RoleProvider 没有被初始化。
  • AccountController 中也不行,所以不能这样。

标签: asp.net-mvc simplemembership


【解决方案1】:

我们使用了System.Web.Security.Roles.GetRolesForUser(...) 调用,然后强力检查这些角色数组是否存在交叉点。在我们的例子中,这一切都发生在自定义的AuthorizeAttribute classes' () 调用中。您可能不需要扩展属性,但我想为以下代码 sn-p 提供一些上下文。我们只使用主体来获取用户名。

例如,

var userRoles = System.Web.Security.Roles.GetRolesForUser(username);
var allowedRoles = Roles.Split(','); // Roles is a property on the Authorize attribute
var matches = userRoles.Intersect(allowedRoles).ToArray();
if ( matches.Length > 0 ) // true if user is in an allowed role, otherwise it is not

希望对您有所帮助!我确信有一种更有效的方法,我刚刚重新整理了我们已经使用了两年的方法。

【讨论】:

    猜你喜欢
    • 2013-03-12
    • 2015-11-06
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 2017-08-20
    • 1970-01-01
    相关资源
    最近更新 更多