Estou implementando uma autenticação com RoleProviderRoleProvider
Customizado.
Tenho uma classe UsuarioUsuario
e uma classe RoleRole
com relacionamento many to many.
Criei uma pasta no projeto chamado SecutirySecurity
e dentro da pasta uma classe chamada PermissaoProviderPermissaoProvider
que estende a classe RoleProviderRoleProvider
.
public override string[] GetRolesForUser(string username)
{
var context = new RdpContext();
var user = context.Usuarios.SingleOrDefault(u => u.Login == username);
if (user == null)
{
return new string[] { };
}
var roles = user.Roles.Select(r => r.Nome).ToList();
return roles.ToArray();
}
public override string[] GetRolesForUser(string username)
{
var context = new RdpContext();
var user = context.Usuarios.SingleOrDefault(u => u.Login == username);
if (user == null)
{
return new string[] { };
}
var roles = user.Roles.Select(r => r.Nome).ToList();
return roles.ToArray();
}
public class PermissoesFiltro : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (Repositorios.UserRepositorio.GetUsuarioLogado() != null)
{
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.HttpContext.Response.Redirect("/admin/Home/Negado");
}
}
else
{
filterContext.HttpContext.Response.Redirect("/admin/login");
}
}
}
public class PermissoesFiltro : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (Repositorios.UserRepositorio.GetUsuarioLogado() != null)
{
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.HttpContext.Response.Redirect("/admin/Home/Negado");
}
}
else
{
filterContext.HttpContext.Response.Redirect("/admin/login");
}
}
}
[PermissoesFiltro(Roles = "ADM, USER")]
public ActionResult Index()
{
return View();
}
[PermissoesFiltro(Roles = "ADM, USER")]
public ActionResult Index()
{
return View();
}
public class UserRepositorio
{
public static Usuario GetUsuarioLogado()
{
var usuario = HttpContext.Current.Request.Cookies["UserCookieAuthentication"];
if (usuario == null)
{
return null;
}
var novoToken = CryptographyRepository.Descriptografar(usuario.Value);
int usuarioId;
return int.TryParse(novoToken, out usuarioId) ? GetUsuarioById(usuarioId) : null;
}
public static Usuario GetUsuarioById(int usuarioId)
{
var context = new RdpContext();
var usuario = context.Usuarios.Include("Roles").FirstOrDefault(u => u.UsuarioId == usuarioId);
return usuario;
}
public static bool AutenticaUsuario(string login, string senha)
{
var ctx = new RdpContext();
ctx.Configuration.ProxyCreationEnabled = false;
try
{
var usuario = ctx.Usuarios.SingleOrDefault(u => u.Login == login && u.Status);
if (usuario == null)
{
return false;
}
if (!Crypto.VerifyHashedPassword(usuario.Senha, senha)) return false;
var userCookie = new HttpCookie("UserCookieAuthentication")
{
Value = CryptographyRepository.Criptografar(usuario.UsuarioId.ToString(CultureInfo.InvariantCulture)),
Expires = DateTime.Now.AddDays(1)
};
HttpContext.Current.Response.Cookies.Add(userCookie);
return true;
}
catch (Exception)
{
return false;
}
}
public static void LogOff()
{
var usuario = HttpContext.Current.Request.Cookies["UserCookieAuthentication"];
if (usuario == null) return;
var userCookie = new HttpCookie("UserCookieAuthentication")
{
Expires = DateTime.Now.AddDays(-1)
};
HttpContext.Current.Response.Cookies.Add(userCookie);
}
}
public class UserRepositorio
{
public static Usuario GetUsuarioLogado()
{
var usuario = HttpContext.Current.Request.Cookies["UserCookieAuthentication"];
if (usuario == null)
{
return null;
}
var novoToken = CryptographyRepository.Descriptografar(usuario.Value);
int usuarioId;
return int.TryParse(novoToken, out usuarioId) ? GetUsuarioById(usuarioId) : null;
}
public static Usuario GetUsuarioById(int usuarioId)
{
var context = new RdpContext();
var usuario = context.Usuarios.Include("Roles").FirstOrDefault(u => u.UsuarioId == usuarioId);
return usuario;
}
public static bool AutenticaUsuario(string login, string senha)
{
var ctx = new RdpContext();
ctx.Configuration.ProxyCreationEnabled = false;
try
{
var usuario = ctx.Usuarios.SingleOrDefault(u => u.Login == login && u.Status);
if (usuario == null)
{
return false;
}
if (!Crypto.VerifyHashedPassword(usuario.Senha, senha)) return false;
var userCookie = new HttpCookie("UserCookieAuthentication")
{
Value = CryptographyRepository.Criptografar(usuario.UsuarioId.ToString(CultureInfo.InvariantCulture)),
Expires = DateTime.Now.AddDays(1)
};
HttpContext.Current.Response.Cookies.Add(userCookie);
return true;
}
catch (Exception)
{
return false;
}
}
public static void LogOff()
{
var usuario = HttpContext.Current.Request.Cookies["UserCookieAuthentication"];
if (usuario == null) return;
var userCookie = new HttpCookie("UserCookieAuthentication")
{
Expires = DateTime.Now.AddDays(-1)
};
HttpContext.Current.Response.Cookies.Add(userCookie);
}
}
<roleManager defaultProvider="PermissaoProvider" enabled="true" cacheRolesInCookie="true">
<providers>
<clear/>
<add name="PermissaoProvider"
type="App.Rdp.Security.PermissaoProvider"
connectionStringName="RdpContext"
applicationName="/"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
writeExceptionsToEventLog="false"/>
</providers>
</roleManager>
<roleManager defaultProvider="PermissaoProvider" enabled="true" cacheRolesInCookie="true">
<providers>
<clear/>
<add name="PermissaoProvider"
type="App.Rdp.Security.PermissaoProvider"
connectionStringName="RdpContext"
applicationName="/"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
writeExceptionsToEventLog="false"/>
</providers>
</roleManager>