Access roles from user authorization attribute

I create my own authorization attribute by overriding the AuthorizeCore method and want to find out if I can access the Roles that were passed to the authorize attribute tag.

So for example, if I have this:

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

Is it possible to access them from inside here:

 protected override bool AuthorizeCore(HttpContextBase httpContext) { } 

Then I could break the string and create an array.

+6
source share
1 answer

You can use this this.Roles , which is the string to be broken.

Source code is freely available.

The default implementation of AuthorizeCore:

 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 separation function that 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(); } 
+9
source

Source: https://habr.com/ru/post/909729/


All Articles