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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With