Ciao,
effettivamente ci saranno più di 100 ruoli quindi devo escludere l'utilizzo dei cookies.
Ho provato a sostituire la CurrentPrincipal con una mia implementazione e sembra funzionare ma resta sempre il problema di dove salvare le roles.
Ho inserito il metodo Application_PostAuthenticateRequest nel global.asax dove vado ad assegnare allo user il mio customPrincipal
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
CustomPrincipal newUser = new CustomPrincipal(HttpContext.Current.User.Identity.Name);
HttpContext.Current.User = newUser;
}
Nel costruttore del CustomPrincipal ho provato ad inserire i ruoli nella cache ma facendo dei test a volte la trovo vuota e va a rieseguire l'accesso al database.
Di seguito uno stralcio dell'implementazione del CustomPrincipal
public class MyRole
{
public string Country { get; set; }
public List<string> Roles { get; set; }
}
public interface ICustomPrincipal : System.Security.Principal.IPrincipal
{
string userID { get; set; }
List<MyRole> MyRoles { get; set; }
}
public class CustomPrincipal : ICustomPrincipal
{
public IIdentity Identity { get; private set; }
private string userRoleCacheKey { get; set; }
public CustomPrincipal(string username)
{
this.userRoleCacheKey = username;
this.Identity = new GenericIdentity(username);
this.userID = username;
List<MyRole> tempMyRole = new List<MyRole>();
if (!TryGetCachedUserRoles(username, out tempMyRole))
{
MyRole myRole = new MyRole();
myRole.Country = GetCountry(username); // Accesso al DB
myRole.Roles = GetUserRoles(username).ToList(); // Accesso al DB
tempMyRole.Add(myRole);
CacheUserRoles(username, tempMyRole);
}
this.MyRoles = tempMyRole;
}
private bool TryGetCachedUserRoles(string username, out List<MyRole> MyRoles)
{
string cacheKey = userRoleCacheKey;
HttpContext httpContext = HttpContext.Current;
if (httpContext != null)
{
MyRoles = (List<MyRole>)httpContext.Cache.Get(cacheKey) ?? new List<MyRole>();
}
else { MyRoles = new List<MyRole>(); }
return MyRoles.Count() > 0;
}
private void CacheUserRoles(string username, List<MyRole> MyRoles)
{
string cacheKey = userRoleCacheKey;
HttpContext httpContext = HttpContext.Current;
if (httpContext != null)
{
httpContext.Cache.Insert(cacheKey, MyRoles, null, DateTime.UtcNow.AddMinutes(15), Cache.NoSlidingExpiration);
}
}
public string userID { get; set; }
public List<MyRole> MyRoles { get; set; }
public bool IsInRole(string role)
{
return Identity != null && Identity.IsAuthenticated &&
!string.IsNullOrWhiteSpace(role) && isInRole(role);
}
private bool isInRole(string role)
{
//TODO
return true;
}
}
Inoltre ho provato a mantenere il CustomRoleProvider e a salvare le roles nella cache ma anche in questo caso si verifica la medesima condizione ((List<MyRole>)httpContext.Cache.Get(cacheKey) = null).
Ti ringrazio per la tua disponibilità