Переопределите User.IsInRole и [Authorize (Roles = «Admin»)] для приложения MVC4
Я создал пользовательский поставщик ролей для своего приложения MVC4, где мне удалось переопределить методы CreateRole, GetAllRoles и RoleExists и связать их с моей существующей базой данных следующим образом:
namespace Project.Providers
{
public class MyProvider : System.Web.Security.SqlRoleProvider
{
private MyContext dbcontext = new MyContext(System.Configuration.ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
private Repository userRepository;
private Repository roleRepository;
public MyProvider()
{
this.userRepository = new Repository(dbcontext);
this.roleRepository = new Repository(dbcontext);
}
public override string[] GetAllRoles()
{
IEnumerable dbRoles = roleRepository.GetAll();
int dbRolesCount = roleRepository.GetAll().Count();
string[] roles = new string[dbRolesCount];
int i = 0;
foreach(var role in dbRoles)
{
roles[i] = role.Name;
i++;
}
return roles;
}
public override bool RoleExists(string roleName)
{
string[] roles = { "Admin", "User", "Business" };
if(roles.Contains(roleName))
return true;
else
return false;
}
public override void CreateRole(string roleName)
{
Role newRole = new Role();
newRole.Name = roleName;
roleRepository.Add(newRole);
roleRepository.SaveChanges();
}
public override bool IsUserInRole(string userName, string roleName)
{
MyUser user = userRepository.Get(u => u.Username == userName).FirstOrDefault();
Role role = roleRepository.Get(r => r.Name == roleName).FirstOrDefault();
if (user.RoleID == role.RoleID)
return true;
else
return false;
}
}
}
Я не смог найти способ переопределить
User.IsInRole(string roleName)
Что еще я должен сделать, чтобы при использовании:
[Authorize(Roles = "Admin")]
Он будет основан на установленном мной поставщике ролей, а не на asp по умолчанию.
Мой пользовательский класс теперь выглядит следующим образом:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Collections;
using System.Security.Principal;
namespace Project.Data
{
public class MyUser : IPrincipal
{
[Key]
public int UserID { get; set; }
[StringLength(128)]
public string Username { get; set; }
.....other properties
public IIdentity Identity { get; set; }
public bool IsInRole(string role)
{
if (this.Role.Name == role)
{
return true;
}
return false;
}
public IIdentity Identity
{
get { throw new NotImplementedException(); }
}
}
}
Моя трассировка стека выглядит следующим образом:
System.Web.Security.RolePrincipal.IsInRole(String role)
Итак, я попытался реализовать пользовательский RolePrincipal таким же образом, как я настраивал пользовательский поставщик. Есть идеи, как мне это сделать? Не уверен, что конструктор params требует. Вот моя попытка:}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration.Provider;
using Project.Data;
using System.Web.Security;
using System.Security.Principal.IIdentity;
namespace Project.Principal
{
public class MyPrincipal : System.Web.Security.RolePrincipal
{
private MyContext dbcontext = new MyContext(System.Configuration.ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
private Repository userRepository;
private Repository roleRepository;
public MyPrincipal()
{
this.userRepository = new Repository(dbcontext);
this.roleRepository = new Repository(dbcontext);
}
public override bool IsInRole(string role)
{
//code to be added
return true;
}
}