Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Roles from Custom Authorize Attribute

I am creating my own custom authorize attribute, overriding the AuthorizeCore method and wanted to know if it is possible to access the Roles which have been passed into the authorize attribute tag.

So for instance if I have this:

[CustomAuthorize(Roles = "Administrator, Sales, Entry")]

Is it possible to access these from inside here:

protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
    }

I could then split the string and create an array.

like image 353
Hesky Avatar asked Mar 01 '12 12:03

Hesky


People also ask

How does the Authorize attribute work?

If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.


1 Answers

You can this this.Roles which is a string that you need to split.

The source code is freely available.

The default AuthorizeCore implementation:

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

And they have an internal split function which looks like this:

internal static string[] SplitString(string original) {
    if (String.IsNullOrEmpty(original)) {
        return new string[0];
    }

    var split = from piece in original.Split(',')
                let trimmed = piece.Trim()
                where !String.IsNullOrEmpty(trimmed)
                select trimmed;
    return split.ToArray();
}
like image 92
jgauffin Avatar answered Oct 11 '22 23:10

jgauffin