public async Task Invoke(HttpContext context, IRoleService roleService) { Endpoint endpoint = context.Features.Get <IEndpointFeature>()?.Endpoint; PermissionAttribute attribute = endpoint?.Metadata.GetMetadata <PermissionAttribute>(); if (attribute != null) { if (context.User.IsAuthenticated() && await context.User.HasPermission(roleService, attribute.Requirement, attribute.Permissions)) { await _next(context); } else { context.Response.StatusCode = 403; await context.Response.WriteAsync("You do not have permission to access this resource."); return; } } if (!context.Response.HasStarted) { await _next(context); } }
private void VerifyPermission(AuthorizationContext filterContext) { object[] attrs = filterContext.ActionDescriptor.GetCustomAttributes(false); for (int i = 0; i < attrs.Length; i++) { object attr = attrs[i]; if (attr is PermissionAttribute) { PermissionAttribute permission = attr as PermissionAttribute; if (!permission.UnverifyByFilter) { string roleKey; if (IsUserSessionOutOfDate(filterContext, out roleKey)) { filterContext.Result = RedirectLoginPage(); } else if (!AuthorizationManager.GetInstance().VerifyPermission(permission.Id, roleKey)) { _httpContext.Response.StatusCode = 403; filterContext.Result = new ViewResult() { ViewName = "NoPermission" }; } } } } }
public override void Begin_Request() { // //UNDONE: Plugin Permission // PermissionAttribute permission = new PermissionAttribute(HttpContext.Current.Request.Path); // permission.Validate(UserState.Administrator.Current); }
private void CheckPermissionAttribute(PermissionAttribute permissionAttribute, XDocument dataTable) { if (!b1DAO.PermissionExists(permissionAttribute)) { var rows = dataTable.Element("DataTable").Element("Rows"); rows.Add(Messages.Permission, permissionAttribute.PermissionID, permissionAttribute.Name); } }
//开始之前执行 public override void Begin_Request() { SiteDto site = CmsWebMaster.CurrentManageSite; if (!(site.SiteId > 0)) throw new Exception("请登陆后再进行操作!"); this.siteId = site.SiteId; PermissionAttribute permission = new PermissionAttribute(HttpContext.Current.Request.Path); permission.Validate(UserState.Administrator.Current); }
static ServicePermissionChecker() { PermissionAttribute permissionAttr = typeof(T).GetCustomAttribute <PermissionAttribute>(); if (permissionAttr is null) { throw new InvalidOperationException($"The type {typeof(T).Name} is not marked with the [{typeof(PermissionAttribute).Name}]. Please define the permission the user need to execute this action."); } permissionId = permissionAttr.PermissionId; }
public string GetPermissionId() { string permissionId = null; PermissionAttribute attribute = GetAttribute(); if (attribute != null) { permissionId = attribute.PermissionId; } return(permissionId); }
public bool HasPermission(AuthorizationContext filterContext, out PermissionAttribute attr) { attr = filterContext.ActionDescriptor.GetCustomAttributes(false).FirstOrDefault(a => a is PermissionAttribute) as PermissionAttribute; if (attr == null) { return(true); } else { return(UserApplication.GetUser <Employee>().HasPermission(attr.Key)); } }
public void RequireCorrectPermission() { string expectedPermission = Permissions.GetUnapprovedSongForPlaying; // Arrange && Act PermissionAttribute attr = typeof(GetUnapprovedSongForPlaying) .GetCustomAttribute <PermissionAttribute>(false); string actualPermission = attr.PermissionId; // Assert Assert.AreEqual(expectedPermission, actualPermission); }
public void RequireCorrectPermission() { string expectedPermission = Permissions.DemoteUserFromRole; // Arrange && Act PermissionAttribute attr = typeof(DemoteUserFromRole) .GetCustomAttribute <PermissionAttribute>(false); string actualPermission = attr.PermissionId; // Assert Assert.AreEqual(expectedPermission, actualPermission); }
void AddPermissions(XElement application) { var assemblyAttrs = Assemblies.SelectMany(path => PermissionAttribute.FromCustomAttributeProvider(Resolver.GetAssembly(path))); // Add unique permissions to the manifest foreach (var pa in assemblyAttrs.Distinct(new PermissionAttribute.PermissionAttributeComparer())) { if (!application.Parent.Descendants("permission").Any(x => (string)x.Attribute(attName) == pa.Name)) { application.AddBeforeSelf(pa.ToElement(PackageName)); } } }
//开始之前执行 public override void Begin_Request() { SiteDto site = CmsWebMaster.CurrentManageSite; if (!(site.SiteId > 0)) { throw new Exception("请登陆后再进行操作!"); } this.siteId = site.SiteId; PermissionAttribute permission = new PermissionAttribute(HttpContext.Current.Request.Path); permission.Validate(UserState.Administrator.Current); }
private void PluginPermissionForms_Load(object sender, EventArgs e) { foreach (PropertyInfo property in typeof(PermissionsHandler).GetProperties()) { PermissionAttribute pAtt = property.GetCustomAttribute(typeof(PermissionAttribute)) as PermissionAttribute; if (pAtt == null) { continue; } if ((bool)property.GetValue(Permissions)) { permissionsList.Items.Add(pAtt.Description); } } }
/// <summary> /// 取页面的所有访问权限 /// </summary> private void LoadPermission() { //通过返射获取此页面的权限属性 MemberInfo memberInfo = this.GetType(); PermissionAttribute permissionAttribute = (PermissionAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(PermissionAttribute)); if (permissionAttribute != null && permissionAttribute.Permissions.Length != 0) { this._permissions = permissionAttribute.Permissions; } else { this._permissions = null; } }
public void NotLoggedIn() { var permissionAttribute = new PermissionAttribute( new List <UserManager.AppPermissions> { UserManager.AppPermissions.AppSettingsWrite } .ToArray()); var authorizationFilterContext = new AuthorizationFilterContext( new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()), new List <IFilterMetadata>()); permissionAttribute.OnAuthorization(authorizationFilterContext); Assert.AreEqual(authorizationFilterContext.Result.GetType(), new UnauthorizedResult().GetType()); }
///<summary> Checks if permission supplied can be converted back to derived type. </summary> private bool ToPermission <T>(PermissionAttribute o, out T result) where T : PermissionAttribute { bool success = false; if (typeof(T).IsAssignableFrom(o.GetType())) { result = (T)o; success = true; } else { result = null; } return(success); }
void AddPermissions(XElement application, List <string> selectedWhitelistAssemblies) { // Look in user assemblies + whitelist (like Maps) var check_assemblies = Assemblies.Union(selectedWhitelistAssemblies); var assemblyAttrs = check_assemblies.SelectMany(path => PermissionAttribute.FromCustomAttributeProvider(Resolver.GetAssembly(path))); // Add unique permissions to the manifest foreach (var pa in assemblyAttrs.Distinct(new PermissionAttribute.PermissionAttributeComparer())) { if (!application.Parent.Descendants("permission").Any(x => (string)x.Attribute(attName) == pa.Name)) { application.AddBeforeSelf(pa.ToElement(PackageName)); } } }
private PermissionAttribute GetAttribute() { PermissionAttribute permissionAttribute = null; MemberInfo info = _instance.GetType(); object[] attributes = info.GetCustomAttributes(false); foreach (Attribute attribute in attributes) { if (attribute is PermissionAttribute) { permissionAttribute = attribute as PermissionAttribute; break; } } return(permissionAttribute); }
public void PermissionClaimMissing() { var permissionAttribute = new PermissionAttribute( new List <UserManager.AppPermissions> { UserManager.AppPermissions.AppSettingsWrite } .ToArray()); var httpContext = new DefaultHttpContext { User = new ClaimsPrincipal(new ClaimsIdentity( new Claim[] { new Claim(ClaimTypes.Name, "username") }, "someAuthTypeName")) }; var authorizationFilterContext = new AuthorizationFilterContext( new ActionContext(httpContext, new RouteData(), new ActionDescriptor()), new List <IFilterMetadata>()); permissionAttribute.OnAuthorization(authorizationFilterContext); Assert.AreEqual(authorizationFilterContext.Result.GetType(), new UnauthorizedResult().GetType()); }
public void SetUp() { _user = new UserInfo { Permissions = new string[0] }; _mockAuth = new Mock <IAuthentication>(); _mockAuth.Setup(m => m.GetUser(It.IsAny <string>())).Returns(_user); var userManager = new UserManager(_mockAuth.Object); var resolver = new NinjectDependencyResolver(); resolver.Kernel.Bind <UserManager>().ToConstant(userManager); DependencyResolver.SetResolver(resolver); _mockCtx = new MockHttpContext(); _mockCtx.SetUser("user"); var controller = new TestController(); var controllerCtx = _mockCtx.CreateControllerContext(controller); var descriptor = new Mock <ActionDescriptor>().Object; _execCtx = new ActionExecutingContext(controllerCtx, descriptor, new Dictionary <string, object>()); _filter = new PermissionAttribute("p1"); }
public object Intercept(IMethodInvocation invocation, params object[] args) { MethodInfo methodInfo = invocation.MethodInvocationTarget; if (!methodInfo.IsDefined(typeof(PermissionAttribute), true)) { return(invocation.Proceed(args)); } else { object[] attrs = methodInfo.GetCustomAttributes(typeof(PermissionAttribute), true); PermissionAttribute permissionAtt = (PermissionAttribute)attrs[0]; ISecurityManager manager = (ISecurityManager)_kernel[typeof(ISecurityManager)]; IPolicy policy = manager.Generate( permissionAtt, Thread.CurrentPrincipal); if (policy == null) { return(invocation.Proceed(args)); } object value = null; if (policy.Evaluate()) { value = invocation.Proceed(args); } else { throw new SecurityException("Not Allowed"); } return(value); } }
public void AddCommand(Command cmdclass, PluginBase plugin) { if (cmdclass == null) { return; } //TODO Notify of Override if (!cmdclass.GetType().IsDefined(typeof(CommandAttribute), true)) { Console.WriteLine("Error Loading Command! Missing Correct Syntax! Command : " + cmdclass.GetType().FullName); return; } PermissionAttribute pa = Attribute.GetCustomAttribute(cmdclass.GetType(), typeof(PermissionAttribute), true) as PermissionAttribute; if (pa != null) { ServerInstance.Instance.PermissionManager.AddPermissionAttribute(pa); } CommandAttribute pluginAttribute = Attribute.GetCustomAttribute(cmdclass.GetType(), typeof(CommandAttribute), true) as CommandAttribute; if (pluginAttribute != null) { cmdclass.Command_Name = pluginAttribute.CommandName; cmdclass.Description = pluginAttribute.Description; cmdclass.UsageMessage = pluginAttribute.Usage; cmdclass.Permissions = pluginAttribute.Permission; cmdclass.PluginName = pluginAttribute.Plugin; cmdclass.ReloadPlugin(); } else //MAYBE if (cmdclass.Permissions == null || cmdclass.Command_Name == null || cmdclass.Description == null || cmdclass.UsageMessage == null)//Skip Console Commands! { Console.WriteLine("Error Loading Command! Error with Syntax! Command : " + cmdclass.GetType().FullName); return; } Console.WriteLine("Loaded Command /" + cmdclass.Command_Name); commandDictionary[cmdclass.Command_Name] = cmdclass.GetType(); }
public void PermissionClaimExist() { var permissionAttribute = new PermissionAttribute( new List <UserManager.AppPermissions> { UserManager.AppPermissions.AppSettingsWrite } .ToArray()); var httpContext = new DefaultHttpContext { User = new ClaimsPrincipal(new ClaimsIdentity( new[] { new Claim("Permission", UserManager.AppPermissions.AppSettingsWrite.ToString()) })) }; var authorizationFilterContext = new AuthorizationFilterContext( new ActionContext(httpContext, new RouteData(), new ActionDescriptor()), new List <IFilterMetadata>()); permissionAttribute.OnAuthorization(authorizationFilterContext); var existHeader = authorizationFilterContext.HttpContext.Response.Headers["x-permission"] == "true"; Assert.IsTrue(existHeader); }
public CommandBuilder AddPermission(PermissionAttribute permission) { Permissions.Add(permission); return(this); }
private PluginInfo ValidatePlugin(String library) { byte[] bytes; Assembly libraryAssembly; try { Console.WriteLine("Loading Plugin Located at " + library); bytes = File.ReadAllBytes(library); libraryAssembly = Assembly.Load(bytes); //Bug Guid is Glitched Right Now //Guid guid = new Guid(((GuidAttribute)libraryAssembly.GetCustomAttributes(typeof(GuidAttribute), true)[0]).Value); bool plug = true; PluginInfo plugin = new PluginInfo(); //Plugin.Guid = guid; plugin.Assembly = libraryAssembly; Command[] CommandList; Type[] PluginTypes = libraryAssembly.GetExportedTypes(); foreach (Type PluginType in PluginTypes) { if (PluginType.BaseType == typeof(Command)) { plugin.FoundCommands.Add(PluginType); //Permissions In Command //Load Permissions foreach (Attribute attribute in PluginType.GetCustomAttributes(true)) { if (attribute is PermissionAttribute) { PermissionAttribute pa = attribute as PermissionAttribute; //Add To plugin //Onplayer Join Event Add Default Perms to player ServerInstance.Instance.PermissionManager.AddPermissionAttribute(pa); } } continue; } if (PluginType.GetInterface(typeof(IPlugin).FullName) != null && plug) { plugin.MainClassType = PluginType; plug = false; continue; } } //B4 resturn Check for Events here //Now Look for Events... IN THE PLUGIN TYPE!!!!!!! //Events if (!plug) { //Loads Events foreach (MethodInfo method in plugin.MainClassType.GetMethods()) { Boolean isevent = false; foreach (Attribute attribute in method.GetCustomAttributes(true)) { if (attribute is HESEventAttribute) { HESEventAttribute hea = attribute as HESEventAttribute; plugin = HandelEvent(method, plugin, hea.EventType); } } } //Load Permissions foreach (Attribute attribute in plugin.GetType().GetCustomAttributes(true)) { if (attribute is PermissionAttribute) { PermissionAttribute pa = attribute as PermissionAttribute; //Add To plugin //Onplayer Join Event Add Default Perms to player ServerInstance.Instance.PermissionManager.AddPermissionAttribute(pa); } } } return(plugin); } catch (Exception ex) { Console.WriteLine("Failed to load assembly: " + library + " Error: " + ex.ToString()); } return(null); }
/// <inheritdoc /> public IFilterMetadata Create(PermissionAttribute attribute) { return(new PermissionValidatorFilter(attribute.Type, attribute.Kind, attribute.Group, _options)); }
public bool InvokeAction(JContext jc) { MethodInfo mi = getActionMethod(jc); if (mi == null) { return(false); } object ret = null; try { if (jc.User != null) { object[] attrs = mi.GetCustomAttributes(typeof(PermissionAttribute), true); if (attrs.Length > 0) { PermissionAttribute attr = attrs[0] as PermissionAttribute; if (!string.IsNullOrEmpty(attr.Permission)) { if (jc.User.HasPermission(attr.Permission)) { goto execute; } else { jc.User.OnPermissionDenied(new PermissionDeniedEventArgs(attr.Permission)); } } } } else { goto execute; } execute: // before execute action Controller.BeforeActionExecuteEventArgs e = new Controller.BeforeActionExecuteEventArgs() { JContext = jc }; jc.Controller.OnBeforeActionExecute(e); Controller.AfterActionExecuteEventArgs e2 = new Controller.AfterActionExecuteEventArgs() { JContext = jc }; if (e.PreventDefault) { ret = e.ReturnValue; } bool support_embed = false; if (jc.IsPost) { jc.RenderContent = false; if (!e.PreventDefault) { NameValueCollection form = jc.Form; // 在post表单中加入key不存在的querystring值 foreach (string key in jc.QueryString.Keys) { if (form[key] == null) { form[key] = jc.QueryString[key]; } } ret = execute(jc.Controller, mi, form); } e2.Result = ret; jc.Controller.OnAfterActionExecute(e2); ret = e2.Result; if (ret != null) { if (ret is ActionResult) { ActionResult actionResult = ret as ActionResult; actionResult.ExecuteResult(jc); } else if (!jc.RenderContent) { ResponseUtil.OutputJson(jc.Context.Response, ret); } } } else { if (!e.PreventDefault) { ret = execute(jc.Controller, mi, jc.QueryString); } e2.Result = ret; jc.Controller.OnAfterActionExecute(e2); ret = e2.Result; if (ret != null) { if (ret is ActionResult) { ActionResult actionResult = ret as ActionResult; actionResult.ExecuteResult(jc); support_embed = ret is ViewResult; } else { jc.RenderContent = false; int cacheMinutes = 0; object[] attrs = mi.GetCustomAttributes(typeof(HttpGetAttribute), false); if (attrs.Length == 1) { cacheMinutes = (attrs[0] as HttpGetAttribute).CacheMinutes; } ResponseUtil.OutputJson(jc.Context.Response, ret, cacheMinutes); } } else { support_embed = true; } } if (support_embed && jc.IsEmbed) { jc.RenderContent = false; ResponseUtil.OutputJson(jc.Context.Response, new TemplatedControl() { UsedInMvc = jc.Context.Request.Headers["usedinmvc"].ToBoolean(true), OverrideSkinName = true, Templated = true }.Execute()); } // 发送控制器执行时间的消息 send_action_execute_msg(jc); } catch (ThreadAbortException) { }// ignore this exception catch (Exception ex) { jc.Controller.OnException(ex); } return(true); }
/// <inheritdoc /> public IFilterMetadata Create(PermissionAttribute attribute) { return(new PassthroughValidator()); }