Windows身份validation并通过数据库添加授权角色 – MVC asp.net

我是mvc4 asp .net的新手,并且与身份validation和授权相混淆。 我们的内部网站从Windows身份validation中获取用户名(HttpContext.Current.User.Identity.Name),如果用户名存在以及用户具有什么角色,则检查数据库。 我想使用全局[Authorize]属性和角色来访问控制器。 任何人都可以帮助我如何开始。

现在,我有一个函数,它传递用户名并从数据库中获取用户数据和相关角色,查询数据被添加到模型中。所以,我使用此函数来访问网站,但我想使用相同的在不查询db的情况下检查所有控制器和视图的数据。

您只需要创建自定义角色提供程序 。 您可以通过创建一个inheritance自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(); } } } 

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

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