Chris
Chris

Reputation: 476

MVC3 AuthorizeAttribute

This allows "frankl" to access but blocks the admins. What have I done wrong?

 [Authorize(Order=1,Roles = "Admin",Users="frankl")]
public class AuthorizeBaseController_Admins_frank : Controller
{

}

It is probably simple but I don't see any examples that combine the two and the "Allowmultiple" property generates an error when I try to add it.

Thanks, Chris

Upvotes: 0

Views: 219

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

Roles and Users should be used exclusively. If you want to combine them you could write a custom authorize attribute:

public class MyAuthoirizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }
        var user = httpContext.User;
        if (!user.Identity.IsAuthenticated)
        {
            return false;
        }
        var usersSplit = SplitString(Users);
        var rolesSplit = SplitString(Roles);

        return
            (usersSplit.Length > 0 && usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) ||
            (rolesSplit.Length > 0 && rolesSplit.Any(user.IsInRole));
    }

    private string[] SplitString(string original)
    {
        if (string.IsNullOrEmpty(original))
        {
            return new string[0];
        }
        return (from piece in original.Split(',')
                let trimmed = piece.Trim()
                where !string.IsNullOrEmpty(trimmed)
                select trimmed).ToArray();
    }
}

and then:

[MyAuthorize(Order = 1, Roles = "Admin", Users="frankl")]
public class AuthorizeBaseController_Admins_frank : Controller
{
    ...    
}

Upvotes: 1

StanK
StanK

Reputation: 4770

Unfortunately the AuthorizeAttribrute will let you either specify valid users, or valid roles - not both. Here is the relevant bit of code from the MVC 3 source.

protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
    if (httpContext == null) {
        throw new ArgumentNullException("httpContext");
    }

    IPrincipal user = httpContext.User;
    if (!user.Identity.IsAuthenticated) {
        return false;
    }

    if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {
        return false;
    }

    if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) {
        return false;
    }

    return true;
}

You will either need to make 'frankl' an Admin, or create a custom authorization attribrute

Upvotes: 0

Related Questions