/// <summary> /// 使用Descriptor,取程序集中所有Action的元数据 /// </summary> /// <returns></returns> public static IEnumerable<ApplicationPermission> GetAllActionByAssembly() { var result = new List<ApplicationPermission>(); //取程序集中的全部类型 var types = Assembly.Load("AspNetIdentity2Permission.Mvc").GetTypes(); //取控制器 foreach (var type in types) { if (type.BaseType == typeof(BaseController))//如果是BaseController { //反射控制器 var controller = new ReflectedControllerDescriptor(type); //取控制器的Action,共有实例方法 var actions = controller.GetCanonicalActions(); //构建权限 foreach (var action in actions) { //创建权限 var ap = new ApplicationPermission() { Action = action.ActionName, Controller = controller.ControllerName, //Params = FormatParams(action), Description = GetDescription(action) }; result.Add(ap); } } } return result; }
public MvcActionFunction(Type controllerType, string actionName, string @namespace, string name, string description, FunctionCollection functionCollection) : base(@namespace, name, description, functionCollection) { _controllerDescriptor = new ReflectedControllerDescriptor(controllerType); _actionName = actionName; var actions = _controllerDescriptor.GetCanonicalActions().Where(a => a.ActionName == actionName); Verify.That(actions.Any(), "Action name '{0}' isn't recognized", actionName); _routeToRender = "~/{0}/{1}".FormatWith(_controllerDescriptor.ControllerName, actionName); }
public ActionResult Redirect() { var catalog = this.Container.Catalog; double lowestOrder = double.MaxValue; Uri redirectUri = null; foreach (var exportInfo in catalog.FindExports<IControllerMetadata>(ContractNames.AdminController)) { ReflectedControllerDescriptor descriptor = new ReflectedControllerDescriptor(exportInfo.Value); var controllerAttr = descriptor.GetCustomAttributes(typeof(AdminControllerAttribute), true).FirstOrDefault() as AdminControllerAttribute; if (controllerAttr == null) continue; if (controllerAttr.Order >= lowestOrder) continue; lowestOrder = controllerAttr.Order; Uri defaultTargetUrl = null; foreach (var actionDescriptor in descriptor.GetCanonicalActions()) { var actionAttr = actionDescriptor.GetCustomAttributes(typeof(AdminActionAttribute), true).FirstOrDefault() as AdminActionAttribute; if (actionAttr == null) continue; string targetUrl = Url.Action(actionAttr.Name, controllerAttr.Name, new { packageId = exportInfo.Metadata.PackageId, packageVersion = exportInfo.Metadata.PackageVersion }); Uri target = new Uri(targetUrl, UriKind.RelativeOrAbsolute); if (defaultTargetUrl == null || actionAttr.IsDefault) defaultTargetUrl = target; } if (defaultTargetUrl != null) redirectUri = defaultTargetUrl; } return Redirect(redirectUri.ToString()); }
public void UpdateActionList() { DB.ControllerActions.ToList(); List<Type> typeList = Assembly.GetExecutingAssembly().GetExportedTypes().Where(r => r.HasBaseType(typeof(Controller))).ToList(); //Delete non-existing controllers foreach (var item in typeList) { ReflectedControllerDescriptor controllerDes = new ReflectedControllerDescriptor(item); string controllerName = controllerDes.ControllerName; ControllerAction controllerOfActionAuthorization = DB.ControllerActions.Where(r => r.Controller == controllerName && string.IsNullOrEmpty(r.Action) && string.IsNullOrEmpty(r.HttpVerb) ).FirstOrDefault(); if (controllerOfActionAuthorization == null) { controllerOfActionAuthorization = new ControllerAction(); controllerOfActionAuthorization.Controller = controllerName; DB.AddToControllerActions(controllerOfActionAuthorization); Save(); } List<ActionDescriptor> actionDescriptorList = controllerDes.GetCanonicalActions().ToList(); foreach (var actionDesc in actionDescriptorList) { string parameters = string.Join(", ", actionDesc.GetParameters().Select(r => r.ParameterName)); string httpVerb = actionDesc.GetHttpVerb(); string actionName = actionDesc.ActionName; ControllerAction actionOfActionAuthorization = DB.ControllerActions.Where(r => r.Controller == controllerName && r.Action == actionName && r.HttpVerb == httpVerb).FirstOrDefault(); if (actionOfActionAuthorization == null) { actionOfActionAuthorization = new ControllerAction(); actionOfActionAuthorization.Controller = controllerName; actionOfActionAuthorization.Action = actionName; actionOfActionAuthorization.Parameters = parameters; actionOfActionAuthorization.HttpVerb = httpVerb; DB.AddToControllerActions(actionOfActionAuthorization); Save(); } } } }
//This method checks if we have an AJAX request or not private bool IsAjaxRequest() { //The easy way bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest") || ((Request.Headers != null) && (Request.Headers["X-Requested-With"] == "XMLHttpRequest")); //If we are not sure that we have an AJAX request or that we have to return JSON //we fall back to Reflection if (!isAjaxRequest) { try { //The controller and action string controllerName = Request.RequestContext. RouteData.Values["controller"].ToString(); string actionName = Request.RequestContext. RouteData.Values["action"].ToString(); //We create a controller instance DefaultControllerFactory controllerFactory = new DefaultControllerFactory(); Controller controller = controllerFactory.CreateController( Request.RequestContext, controllerName) as Controller; //We get the controller actions ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType()); ActionDescriptor[] controllerActions = controllerDescriptor.GetCanonicalActions(); //We search for our action foreach (ReflectedActionDescriptor actionDescriptor in controllerActions) { if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper())) { //If the action returns JsonResult then we have an AJAX request if (actionDescriptor.MethodInfo.ReturnType .Equals(typeof(JsonResult))) return true; } } } catch(Exception eeee) { log.Exception(eeee); } } return isAjaxRequest; }
private void ListValidActions(RequestContext requestContext) { ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(typeof(HomeController)); ActionDescriptor[] actionDescriptors = controllerDescriptor.GetCanonicalActions(); if (actionDescriptors.Any()) { foreach (ActionDescriptor actionDescriptor in actionDescriptors) { requestContext.HttpContext.Response.Write(actionDescriptor.ActionName + "<br/>"); } } else { requestContext.HttpContext.Response.Write("无合法的Action方法"); } }
//FROM: http://stackoverflow.com/questions/2721869/security-aware-action-link public static bool CheckHasActionPermission(ViewContext viewContext, string actionName, string controllerName = null, bool useNamespaceFallback = false) { //if the controller name is empty the ASP.NET convention is: //"we are linking to a different controller ControllerBase controllerToLinkTo = string.IsNullOrEmpty(controllerName) ? viewContext.Controller : GetControllerByName(viewContext, controllerName, useNamespaceFallback); var controllerContext = new ControllerContext(viewContext.RequestContext, controllerToLinkTo); var controllerDescriptor = new ReflectedControllerDescriptor(controllerToLinkTo.GetType()); var actionDescriptor = controllerDescriptor.GetCanonicalActions().Where(x => String.Equals(x.ActionName, actionName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); //Originally it was: //var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName); //I changed it because, I want to check accessibility to an POST action. Maybe it could fail for actions for different http method and the same name return ActionIsAuthorized(controllerContext, actionDescriptor); }
/// <summary> /// Checks if user has enough permissions to action from controller. /// </summary> /// <param name="htmlHelper"></param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of controller. If empty, uses current controller.</param> /// <returns></returns> public static bool ActionAuthorized(this HtmlHelper htmlHelper, string actionName, string controllerName) { ControllerBase controllerBase = string.IsNullOrEmpty(controllerName) ? htmlHelper.ViewContext.Controller : htmlHelper.GetControllerByName(controllerName); ControllerContext controllerContext = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerBase); ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerContext.Controller.GetType()); ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName); if (actionDescriptor == null) { actionDescriptor = controllerDescriptor.GetCanonicalActions().Where(a => a.ActionName == actionName).FirstOrDefault(); } if (actionDescriptor == null) return false; FilterInfo filters = new FilterInfo(FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor)); AuthorizationContext authorizationContext = new AuthorizationContext(controllerContext, actionDescriptor); foreach (IAuthorizationFilter authorizationFilter in filters.AuthorizationFilters) { authorizationFilter.OnAuthorization(authorizationContext); if (authorizationContext.Result != null) return false; } return true; }
private Dictionary<string, List<string>> GetAllControllersAndActions() { var controllersAndActions = new Dictionary<string, List<string>>(); foreach (var controller in GetControllers()) { var newDictionaryEntry = new KeyValuePair<string, List<string>>(controller.Name, new List<string>()); var controllerDescriptor = new ReflectedControllerDescriptor(controller); ActionDescriptor[] actions = controllerDescriptor.GetCanonicalActions(); foreach (var action in actions) { var paramSignatureString = GetParamSignatureString(action); newDictionaryEntry.Value.Add(action.ActionName + paramSignatureString); //controllersAndActions.Add(action.ControllerDescriptor.ControllerName + " -> " + action.ActionName + paramSignatureString); } controllersAndActions.Add(newDictionaryEntry.Key, newDictionaryEntry.Value); } return controllersAndActions; }
public bool ControllerContainsAction(Type controller, string routedAction, string requestedHttpMethod) { // Get a descriptor of this controller var controllerDesc = new ReflectedControllerDescriptor(controller); // Look at each action in the controller foreach (var action in controllerDesc.GetCanonicalActions()) { var currentControllerActionHttpAttributes = action.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true).Cast<ActionMethodSelectorAttribute>().ToList(); // 1) Does the controller have an action with the requested httpMethod. if (action.ActionName.Equals(requestedHttpMethod, StringComparison.InvariantCultureIgnoreCase)) return true; // 2) Does the controller have an action with the name of the routedAction and ((a matching HTTPMethod attributed) or (no attribute and the default requested HTTPMethod of GET)). if( action.ActionName.Equals(routedAction, StringComparison.InvariantCultureIgnoreCase) && (currentControllerActionHttpAttributes.Any(a=> a.ToString().ToLower().Contains(requestedHttpMethod.ToLower())) || (!currentControllerActionHttpAttributes.Any() && requestedHttpMethod.Equals("GET",StringComparison.InvariantCultureIgnoreCase) )) ) return true; } return false; }
public void OnActionExecuted(ActionExecutedContext filterContext) { ViewResult viewResult = filterContext.Result as ViewResult; if (viewResult != null && viewResult.Model != null) { IAdminModel model = viewResult.Model as IAdminModel; if (model == null) throw new InvalidOperationException(string.Format("Model ({0}) does not implement IAdminModel", viewResult.GetType().Name)); model.Notifications = App.Instance.Notifications.Get(filterContext.HttpContext.User); // this was populated by the AddInControllerFactory IControllerMetadata metadata = (IControllerMetadata) filterContext.RequestContext.HttpContext.Items[AddInControllerFactory.MetadataKey]; string actionText = string.Empty; // TODO FIX THIS SOMEHOW, this is pretty crappy var allControllerExports = App.Instance.Container.GetExports( new ContractBasedImportDefinition( ContractNames.AdminController, AttributedModelServices.GetTypeIdentity(typeof(IController)), Enumerable.Empty<KeyValuePair<string, Type>>(), ImportCardinality.ZeroOrMore, false, false, CreationPolicy.NonShared)); List<Navigation> menu = new List<Navigation>(); foreach (Export export in allControllerExports) { IControllerMetadata controllerMetadata = AttributedModelServices.GetMetadataView<IControllerMetadata>(export.Metadata); ReflectedControllerDescriptor descriptor = new ReflectedControllerDescriptor(export.Value.GetType()); var controllerAttr = descriptor.GetCustomAttributes(typeof(AdminControllerAttribute), true).FirstOrDefault() as AdminControllerAttribute; if (controllerAttr == null) continue; UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext); Uri defaultTargetUrl = null; List<Navigation> children = new List<Navigation>(); foreach (var actionDescriptor in descriptor.GetCanonicalActions()) { var actionAttr = actionDescriptor.GetCustomAttributes(typeof(AdminActionAttribute), true).FirstOrDefault() as AdminActionAttribute; if (actionAttr == null) continue; // TODO replace anon class with concrete type? string targetUrl = urlHelper.Action(actionAttr.Name, controllerAttr.Name, new { packageId = controllerMetadata.PackageId, packageVersion = controllerMetadata.PackageVersion }); Uri target = new Uri(targetUrl, UriKind.RelativeOrAbsolute); if (defaultTargetUrl == null || actionAttr.IsDefault) defaultTargetUrl = target; bool isActive = filterContext.ActionDescriptor.ActionName == actionDescriptor.ActionName && filterContext.ActionDescriptor.ControllerDescriptor.ControllerType == descriptor.ControllerType; if (isActive) actionText = actionAttr.Text; Navigation navigation = new Navigation(null, actionAttr.Order, actionAttr.Text, target, isActive, Enumerable.Empty<Navigation>()); children.Add(navigation); } bool isAnyChildActive = children.Any(n => n.IsActive); // if there's only one child, ignore it if (children.Count == 1) children.Clear(); menu.Add(new Navigation(controllerAttr.Group, controllerAttr.Order, controllerAttr.Text, defaultTargetUrl, isAnyChildActive, children)); } model.Navigation = menu.OrderBy(n => n.Order).ToArray(); model.PageTitle = "LostDoc Administration " + metadata.Text; if (!string.IsNullOrWhiteSpace(actionText)) model.PageTitle += string.Format(" - {0}", actionText); } }
/// <summary> /// Saúl H. Sánchez. /// /// Metodo utilizado para inicializar la configuración del /// plugin WebSecurity, y la inicialización de la conexión /// de la base de datos, tomando en cuenta la tabla de la /// base de datos que almacenará los datos de los usuarios /// de la aplicación. También en este método se insertan los /// datos por defecto requeridos para el mínimo funcionamiento /// de la aplicación, tales como roles y un usuario por defecto. /// </summary> public static void Register() { try { WebSecurity.InitializeDatabaseConnection ( "SigeretContext", "UserProfile", "UserId", "username", autoCreateTables: true ); //verificacion y creacion de roles de la aplicacion var roles = (SimpleRoleProvider)Roles.Provider; if (roles.GetAllRoles().Count() == 0) { roles.CreateRole("Administrador"); roles.CreateRole("Profesor"); roles.CreateRole("Estudiante"); } //Creacion y gestion de parametros para cuenta administrador if (!WebSecurity.UserExists("SigeretAdmin")) { WebSecurity.CreateUserAndAccount( "SigeretAdmin", "000000", propertyValues: new { Nombre = "Administrador", Apellido = "Sigeret", Cedula = "00000000000", Matricula = "7777777777" }); } if (!roles.GetRolesForUser("SigeretAdmin").Contains("Administrador")) { roles.AddUsersToRoles(new[] { "SigeretAdmin" }, new[] { "Administrador" }); } using (SigeretContext db = new SigeretContext()) { //Almacenando datos de los controladores y la acciones en la bd, para el modulo de permisos. var types = from a in AppDomain.CurrentDomain.GetAssemblies() from t in a.GetTypes() where typeof(IController).IsAssignableFrom(t) select t; foreach (var ctrlType in types) { ReflectedControllerDescriptor ctrlDescriptor = new ReflectedControllerDescriptor(ctrlType); if (ctrlDescriptor.GetCustomAttributes(typeof(EsControllerAttribute), false).Any()) { var attribute = ctrlDescriptor.GetCustomAttributes(typeof(EsControllerAttribute), false).FirstOrDefault() as EsControllerAttribute; Controlador ctrl = db.Controladors.FirstOrDefault(c => c.Descriptor == attribute.Descriptor); if (ctrl == null) { ctrl = new Controlador(); ctrl.Name = attribute.ControllerName; ctrl.Descriptor = attribute.Descriptor; db.Controladors.Add(ctrl); } else { if (ctrl.Name != attribute.ControllerName) { ctrl.Name = attribute.ControllerName; } db.Entry(ctrl).State = System.Data.EntityState.Modified; } foreach (ActionDescriptor ad in ctrlDescriptor.GetCanonicalActions()) { if (ad.GetCustomAttributes(typeof(VistaAttribute), false).Any()) { var ActionAttribute = ad.GetCustomAttributes(typeof(VistaAttribute), false).FirstOrDefault() as VistaAttribute; Accion acc = db.Accions.FirstOrDefault(a => a.Descriptor == ActionAttribute.Descriptor); if (acc == null) { acc = new Accion(); acc.Name = ActionAttribute.ViewName; acc.Descriptor = ActionAttribute.Descriptor; ctrl.Accions.Add(acc); db.Accions.Add(acc); } else { if (acc.Name != ActionAttribute.ViewName) { acc.Name = ActionAttribute.ViewName; } db.Entry(acc).State = System.Data.EntityState.Modified; } } } db.SaveChanges(); } } //Asignando permisos sobre todas las acciones a la cuenta de Administrador por defecto. var adminRole = db.webpages_Roles.FirstOrDefault(r => r.RoleName == "Administrador"); foreach (Accion a in db.Accions) { if (!adminRole.Accions.Contains(a)) adminRole.Accions.Add(a); } db.Entry(adminRole).State = System.Data.EntityState.Modified; db.SaveChanges(); } } catch (Exception ex) { throw new InvalidOperationException("No se pudo inicializar la conexión con la base de datos.", ex); } }
private static Navigation[] BuildMenu(ActionExecutedContext filterContext, ComposablePartCatalog catalog, out Navigation active) { active = null; List<Navigation> menu = new List<Navigation>(); foreach (var exportInfo in catalog.FindExports<IControllerMetadata>(ContractNames.AdminController)) { ReflectedControllerDescriptor descriptor = new ReflectedControllerDescriptor(exportInfo.Value); var controllerAttr = descriptor.GetCustomAttributes(typeof(AdminControllerAttribute), true).FirstOrDefault() as AdminControllerAttribute; if (controllerAttr == null) continue; UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext); Uri defaultTargetUrl = null; List<Navigation> children = new List<Navigation>(); foreach (var actionDescriptor in descriptor.GetCanonicalActions()) { var actionAttr = actionDescriptor.GetCustomAttributes(typeof(AdminActionAttribute), true).FirstOrDefault() as AdminActionAttribute; if (actionAttr == null) continue; // TODO replace anon class with concrete type? string targetUrl = urlHelper.Action(actionAttr.Name, controllerAttr.Name, new { packageId = exportInfo.Metadata.PackageId, packageVersion = exportInfo.Metadata.PackageVersion }); Uri target = new Uri(targetUrl, UriKind.RelativeOrAbsolute); if (defaultTargetUrl == null || actionAttr.IsDefault) defaultTargetUrl = target; bool isActive = filterContext.ActionDescriptor.ActionName == actionDescriptor.ActionName && filterContext.ActionDescriptor.ControllerDescriptor.ControllerType == descriptor.ControllerType; Navigation navigation = new Navigation(null, actionAttr.Order, actionAttr.Text, target, isActive, Enumerable.Empty<Navigation>()); if (isActive) active = navigation; children.Add(navigation); } bool isAnyChildActive = children.Any(n => n.IsActive); // if there's only one child, ignore it if (children.Count == 1) children.Clear(); menu.Add(new Navigation(controllerAttr.Group, controllerAttr.Order, controllerAttr.Text, defaultTargetUrl, isAnyChildActive, children)); } var navigations = menu.OrderBy(n => n.Order).ToArray(); return navigations; }