Mam app MVC i napisałem niestandardową roleprovider dla niego, jak pokazano:MVC niestandardowy roleprovider jak go podłączyć do HttpContext.Current.User.IsInRole ("myrole")
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using VectorCheck.Models;
namespace VectorCheck.Security
{
public class MyRoleProvider : RoleProvider
{
private VectorCheckRepository<User> _repository { get; set; }
public MyRoleProvider()
{
_repository = new VectorCheckRepository<User>();
}
public MyRoleProvider(VectorCheckRepository<User> repository)
{
_repository = repository;
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
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)
{
var user = _repository.GetUser(username);
return new string[] { user.Role.Name };
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override bool IsUserInRole(string username, string roleName)
{
var user = _repository.GetUser(username);
return string.Compare(user.Role.Name, roleName, true) == 0;
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}
To naprawdę działa dobrze z ograniczeniem dostępu do kontrolerów i działań przy użyciu:
[Authorize(Roles = "Administrator")]
powyżej kontrolera lub działania.
Chcę również ograniczony dostęp do niektórych rzeczy w widoku choć używając:
HttpContext.Current.User.IsInRole("Administrator")
Metoda ta nie jest częścią mojego roleprovider chociaż tak nie jest uzyskiwanie nadpisane.
Czy ktoś wie, jak to zrobić dla tej metody?
mojego dostawcy rola nie zawiera metodę IsInRole chociaż. Dziedziczy po RoleProvider i ma metodę IsUserInRole. – AnonyMouse
Metoda IsInRole na HttpContext.Current.User jest na typ implementujący IPrincipal. Jeśli masz zarejestrowanego RoleProvider, a żądanie pochodzi od uwierzytelnionego użytkownika, IPrincipal będzie instancją RolePrincipal. Z powyższej metody widać, że IsInRole na RolePrincipal wywołuje metodę GetRolesForUser RoleProvider, więc jest to ta, której potrzebujesz do ustawienia punktu przerwania, aby zapewnić, że jest poprawnie wywoływana. –