public static RolesForMethod GetRolesForMethod(MethodInfoData method) { var method_roles = new RolesForMethod { MethodName = method.methodInfo.Name, Roles = new string[0], IsRolesOverride = false }; var roles_list = new LinkedList <string>(); //the override attribute replaces all other roles for the method var override_roles = method.methodInfo.GetCustomAttribute <OverrideAuthorizeAttribute>(false); if (override_roles != null) { method_roles.IsRolesOverride = true; method_roles.Roles = override_roles.Roles.Select(a => a.Trim()).Distinct().ToArray(); return(method_roles); } var attrs = method.methodInfo.GetCustomAttributes(typeof(AuthorizeAttribute), false).OfType <AuthorizeAttribute>(); if (attrs.Count() == 0) { //allow unauthenticated access var passthrough_attrs = method.methodInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), false) .OfType <AllowAnonymousAttribute>(); if (passthrough_attrs.Any()) { roles_list.AddLast(ALLOW_ANONYMOUS); } } else { //at least user must be authenticated roles_list.AddLast(AUTHENTICATED); foreach (var attr in attrs) { var attr_roles = attr.Roles.Select(a => a.Trim()); foreach (var role in attr_roles) { roles_list.AddLast(role); } } } method_roles.Roles = roles_list.Distinct().ToArray(); return(method_roles); }
public static IEnumerable<RolesForMethod> GetRolesForMethods(IEnumerable<MethodInfo> methods) { RolesForMethod[] result= new RolesForMethod[methods.Count()]; int i=0; foreach (MethodInfo methInfo in methods) { RolesForMethod method_roles = new RolesForMethod { MethodName = methInfo.Name, Roles = null, IsRolesOverride=false }; var roles_list = new LinkedList<string>(); //the override attribute replaces all other roles for the method var override_roles = methInfo.GetCustomAttribute<OverrideAuthorizeAttribute>(false); if (override_roles != null) { method_roles.IsRolesOverride = true; method_roles.Roles = override_roles.Roles.Select(a => a.Trim()).Distinct().ToArray(); result[i++] = method_roles; continue; } var attrs = methInfo.GetCustomAttributes(typeof(AuthorizeAttribute), false).OfType<AuthorizeAttribute>(); if (attrs.Count() == 0) { //allow unauthenticated access var passthrough_attrs = methInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).OfType<AllowAnonymousAttribute>(); if (passthrough_attrs.Count()> 0) roles_list.AddLast(ALLOW_ANONYMOUS); } else { //at least user must be authenticated roles_list.AddLast(AUTHENTICATED); foreach (var attr in attrs) { var attr_roles = attr.Roles.Select(a => a.Trim()); foreach (var role in attr_roles) roles_list.AddLast(role); } } method_roles.Roles = roles_list.Distinct().ToArray(); result[i++] = method_roles; } return result; }