C# Windows身份验证和通过数据库添加授权角色-MVC asp.net
我是MVC4ASP.net新手,对身份验证和授权感到困惑。我们的是一个内部网站,它从windows身份验证中获取用户名(HttpContext.Current.User.Identity.Name),并根据数据库检查用户名是否存在以及用户具有哪些角色。我想使用全局[Authorize]属性和角色来授予控制器访问权限。有人能帮我从什么开始吗 现在,我有一个传递用户名的函数,从数据库中获取用户数据和相关角色,查询数据被添加到模型中。因此,我使用此函数访问网站,但我希望使用相同的数据检查所有控制器和视图,而不必一直查询数据库 你只需要这样做。您可以通过创建一个继承自C# Windows身份验证和通过数据库添加授权角色-MVC asp.net,c#,asp.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,我是MVC4ASP.net新手,对身份验证和授权感到困惑。我们的是一个内部网站,它从windows身份验证中获取用户名(HttpContext.Current.User.Identity.Name),并根据数据库检查用户名是否存在以及用户具有哪些角色。我想使用全局[Authorize]属性和角色来授予控制器访问权限。有人能帮我从什么开始吗 现在,我有一个传递用户名的函数,从数据库中获取用户数据和相关角色,查询数据被添加到模型中。因此,我使用此函数访问网站,但我希望使用相同的数据检查所有控制器和视
System.Web.Security.RoleProvider
的类并重写某些成员来实现这一点。下面的代码应该可以帮助您开始。用函数的实现替换所有抛出新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
或DeleteRole
执行任何操作
您还需要向ASP.NET framework注册您的角色提供程序,以便它知道如何使用它。更新您的web.config
,如下所示
<configuration>
<system.web>
<roleManager defaultProvider="MyRoleProvider" enabled="true">
<providers>
<add
name="MyRoleProvider"
type="MyNamespace.MyRoleProvider"
applicationName="MyApplicationName" />
</providers>
</roleManager>
</system.web>
</configuration>
非常感谢。。我会从这个开始,让你知道如果我有任何问题,请告诉我如何称呼这个。。。像[Authorize(在这里调用什么来检查角色)]@GiGi假设您已经实现了我所描述的角色管理器,那么您可以对控制器中的操作方法执行类似于[Authorize(Roles=“Administrators”)]
的操作,这将限制它,以便只有“Administrators”中的用户可以访问该操作方法。请参阅。我收到了此错误,因此我正在检查如何修复此错误..“在应用程序级别之外使用注册为allowDefinition='MachineToApplication'的节是一个错误。此错误可能是由于虚拟目录未在IIS中配置为应用程序造成的。”各位,请确保“启用”角色管理器功能。如果未启用角色管理器功能,则必须在web.config文件的rolemanager节点上设置enabled=“true”。