Custom RoleProvider

6

I'm implementing authentication with% custom%.

I have a class RoleProvider and a class Usuario with many to many relationship.

I created a folder in the project called Role and within the folder a class named Security that extends the class PermissaoProvider .

The only method I subscribed to is the method below:

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();
} 

I also created a class called PermissionsFilter that follows below:

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");
        }
    }
}

And so I decorate my Controller as follows:

[PermissoesFiltro(Roles = "ADM, USER")]
public ActionResult Index()
{
    return View();
}

Authentication happens normally, but regardless of which user logs in and always redirected to the denied access page, below is the authentication methods below.

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);
    }
}

I also configured web.config as follows:

<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>

I'm 2 days searching and I can not find a solution.

    
asked by anonymous 11.03.2014 / 00:16

1 answer

2

The problem is in its PermissoesFiltro : the OnAuthorize event calls another called AuthorizeCore , which effectively calculates the permission. I would make your override like this:

public class PermissoesFiltro : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var baseReturn = base.AuthorizeCore(httpContext);

        var permissionsReturn = false;
        /* Insira aqui sua lógica para modificar permissionsReturn para true */

        return baseReturn && permissionsReturn;
    }
}
    
11.03.2014 / 00:25