Windows身份验证并通过数据库添加授权角色 - MVC asp.net

2024-04-20

我是 mvc4 asp .net 的新手,对身份验证和授权感到困惑。我们的网站是一个内部网站,它从 Windows 身份验证中获取用户名(HttpContext.Current.User.Identity.Name),并检查数据库是否存在用户名以及用户具有什么角色。我想使用全局 [Authorize] 属性和角色来授予对控制器的访问权限。谁能帮助我如何开始。

目前,我有一个函数可以传递用户名并从数据库中获取用户数据和相关角色,查询数据将添加到模型中。因此,我使用此函数来访问网站,但我想使用相同的功能数据来检查所有控制器和视图,而无需始终查询数据库。


你只需要创建自定义角色提供者 https://msdn.microsoft.com/en-us/library/8fw7xh74.aspx。您可以通过创建一个继承自的类来做到这一点System.Web.Security.RoleProvider并凌驾于某些成员之上。下面的代码应该可以帮助您入门。更换所有throw new NotImplementedException()与你的函数实现有关的东西。例如,IsUserInRole您将提供代码来查询数据库以查看用户是否具有指定的角色。

using System.Web.Security;

namespace MyNamespace
{        
    public class MyRoleProvider : RoleProvider
    {
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName
        {
           get; set;
        }

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            throw new NotImplementedException();
        }

        public override string[] GetRolesForUser(string username)
        {
            throw new NotImplementedException();
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            throw new NotImplementedException();
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException();
        }
    }
}

您可能不需要实施所有这些。例如,如果您的应用程序不会创建或删除角色,则无需执行任何操作CreateRole or DeleteRole.

您还需要向 ASP.NET 框架注册您的角色提供程序,以便它知道如何使用它。更新你的web.config像下面这样。

<configuration>
    <system.web>
        <roleManager defaultProvider="MyRoleProvider" enabled="true">
            <providers>
                <add
                    name="MyRoleProvider"
                    type="MyNamespace.MyRoleProvider"           
                    applicationName="MyApplicationName" />
            </providers>
        </roleManager>
    </system.web>
</configuration>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Windows身份验证并通过数据库添加授权角色 - MVC asp.net 的相关文章

随机推荐