ASP NET MVC Authentication

2

What better way to separate permissions for logged in users? Was it using annotations and roles? Because I want to release certain pages and certain functions depending on the permission of the logged in user.

Someone could tell me better how it could be done and if you have any examples.

The permission table I have in the database is a table with an ID and a Name only, there in the user table there is a field that gets the name of the permissions separated by commas.

    
asked by anonymous 30.07.2015 / 20:43

1 answer

2

Basically, writing your own authorization attribute. For example:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class MeuAuthorize : AuthorizeAttribute
{
    private String[] _permissoes;
    private MeuProjetoContext contexto = new MeuProjetoContext();

    public CustomAuthorizeAttribute(params String[] permissoes) 
    {
        _permissoes = permissoes;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var baseReturn = base.AuthorizeCore(httpContext);

        var permissoesReturn = false;
        var permissoesUsuario = contexto.Permissoes.Where(p => p.Usuario.Nome == httpContext.User.Identity.Name).Select(p => NomePermissao).ToList();
        permissoesReturn = permissoesUsuario.Intersect(_permissoes.OfType<String>().ToList()).Any();

        return permissionsReturn || baseReturn;
    }
}

Usage:

[MeuAuthorize("Usuário", "Gerente", "Administrador")]
public ActionResult MinhaAction() { ... }

Can be used without parameters, just to check if it is logged in:

[MeuAuthorize]
public ActionResult MinhaAction() { ... }
    
30.07.2015 / 22:16