這裏是我使用的RoleProvider
,如果任何人有同樣的瑣碎的要求。如果您知道此實施不安全的原因,請告訴我。我在我的Web.Config中使用@ Pluc的答案將此提供程序連接到我的應用程序。它奇妙地工作。
public class AppRole : IRole<int>
{
public AppRole(int a_id, string a_name)
{
Id = a_id;
Name = a_name;
}
public int Id { get; private set; }
public string Name { get; set; }
}
public class AppRoleProvider : RoleProvider
{
private readonly IServiceLocator _container = UnityConfig.GetServiceLocator();
private ITrainingRepository _repository; // Thin wrapper around my DbContext
private AppRole[] _roles = new[]
{
new AppRole(0, "User"),
new AppRole(5, "Admin"),
};
public AppRoleProvider()
{
ApplicationName = "TrainingCenter";
_repository = _container.GetInstance<ITrainingRepository>();
}
public override string ApplicationName { get; set; }
public override bool IsUserInRole(string username, string roleName)
{
var user = _repository.GetUserByUserName(username);
if (user == null)
return false;
var role = _roles.FirstOrDefault(i => i.Name.Equals(roleName, StringComparison.OrdinalIgnoreCase));
if (role == null)
return false;
if (user.UserLevel >= role.Id)
return true;
return false;
}
public override string[] GetRolesForUser(string username)
{
var user = _repository.GetUserByUserName(username);
if (user == null)
return new string[] {};
return _roles.Where(i => i.Id <= user.UserLevel).Select(i => i.Name).ToArray();
}
public override void CreateRole(string roleName)
{
// Does not create.
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
// Does not delete.
return false;
}
public override bool RoleExists(string roleName)
{
return _roles.Any(i => i.Name.Equals(roleName, StringComparison.OrdinalIgnoreCase));
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
// Does not add user to role.
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
// Does not remove users from roles.
}
public override string[] GetUsersInRole(string roleName)
{
// Does not get users in role.
return new string[] {};
}
public override string[] GetAllRoles()
{
return _roles.Select(i => i.Name).ToArray();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
// Does not find users in role.
return new string[] { };
}
}
我可以在ASP.NET Identity 2.0中使用它嗎? – Jordan
我不明白爲什麼不。它仍然使用AuthorizeAttribute,這意味着它仍然使用角色並需要RoleManager。你爲什麼不試試並告訴我?我從來沒有與身份2.0 – Pluc
不合作。我得到了異常「提供者必須實現類」System.Web.Security.RoleProvider「。」似乎不適用於身份。 – Jordan