private void AddPageTypePropertyDefinitions(IEnumerable<PropertyInfo> properties, ICollection<AuthorizedPropertyDefinition> definitions, TabDefinitionCollection tabDefinitions, string hierarchy, AuthorizeAttribute propertyGroupAuthorizeAttribute) { var pageTypeProperties = properties.Where(AttributedTypesUtility.PropertyHasAttribute<PageTypePropertyAttribute>).ToList(); foreach (PropertyInfo property in pageTypeProperties) { AuthorizeAttribute attribute = AttributedTypesUtility .GetAttributesFromProperty<AuthorizeAttribute>(property) .FirstOrDefault(); // if property has an authorize attribute if (attribute != null) { definitions.Add(AuthorizedPropertyDefinitionFactory.Create(string.Concat(hierarchy, property.Name), attribute.GetAuthorizedPrincipals())); continue; } // Add any tab authorization rules if (AddTabAuthorizationRules(tabDefinitions, property, definitions, hierarchy)) continue; // if property group authorize attribute has been defined then apply to property if (propertyGroupAuthorizeAttribute != null) { definitions.Add(AuthorizedPropertyDefinitionFactory.Create(string.Concat(hierarchy, property.Name), propertyGroupAuthorizeAttribute.GetAuthorizedPrincipals())); continue; } // if the page type class has an authorize attribute if (HasClassLevelAttribute) definitions.Add(AuthorizedPropertyDefinitionFactory.Create(string.Concat(hierarchy, property.Name), ClassAttribute.GetAuthorizedPrincipals())); } }
private static string AuthorizeAttributeAndPolicyNameForDisplay(AuthorizeAttribute attribute) { var policyIfAvailable = string.IsNullOrEmpty(attribute.Policy) ? string.Empty : $" (Policy = {attribute.Policy})"; //space before is by intention return($"[{attribute.GetType().Name}{policyIfAvailable}]"); }
public void AllowRequest_Sets_Status_401_If_Request_Is_Rejected() { var attr = new AuthorizeAttribute(); attr.AllowRequest(_Environment.Environment); Assert.AreEqual(401, _Environment.ResponseStatusCode); }
public void UsersProperty() { // Arrange AuthorizeAttribute attr = new AuthorizeAttribute(); // Act & assert MemberHelper.TestStringProperty(attr, "Users", String.Empty); }
/// <summary> /// Check to see if a method requires authorization for the roles and users specified /// </summary> /// <param name="controller"></param> /// <param name="methodName"></param> /// <param name="methodTypes">Optional</param> /// <param name="roles"></param> /// <param name="users"></param> /// <returns></returns> public static bool IsAuthorized(Type controller, string methodName, Type[] methodTypes, string[] roles, string[] users) { if (roles == null && users == null) { return(IsAuthorized(controller, methodName, methodTypes)); } if (!IsAuthorized(controller, methodName, methodTypes)) { return(false); } AuthorizeAttribute controllerAttribute = GetControllerAttribute <AuthorizeAttribute>(controller); AuthorizeAttribute methodAttribute = GetMethodAttribute <AuthorizeAttribute>(controller, methodName, methodTypes); // Check to see if all roles are authorized if (roles != null) { foreach (string role in roles) { string lowerRole = role.ToLower(); bool roleIsAuthorized = (controllerAttribute != null ? controllerAttribute.Roles.ToLower().Split(',').Any(r => r == lowerRole) : false) || (methodAttribute != null ? methodAttribute.Roles.ToLower().Split(',').Any(r => r == lowerRole) : false); if (!roleIsAuthorized) { return(false); } } } // Check to see if all users are authorized if (users != null) { foreach (string user in users) { string lowerUser = user.ToLower(); bool userIsAuthorized = (controllerAttribute != null ? controllerAttribute.Policy.ToLower().Split(',').Any(u => u == lowerUser) : false) || (methodAttribute != null ? methodAttribute.Policy.Split(',').Any(u => u.ToLower() == lowerUser) : false); if (!userIsAuthorized) { return(false); } } } return(true); }
public void RefreshTokenAsync_should_not_have_authorize_attribute() { // Assert Type controllerType = typeof(AuthController); MethodBase methodBase = controllerType.GetMethod(nameof(_authController.RefreshTokenAsync)); AuthorizeAttribute authorizeAttribute = methodBase.GetCustomAttribute <AuthorizeAttribute>(); Assert.IsFalse(authorizeAttribute != null); }
public void OnAuthorization(AuthorizationFilterContext context) { try { AuthorizeAttribute authAttribute = (AuthorizeAttribute)context.ActionDescriptor.EndpointMetadata.Where(e => e.GetType() == typeof(AuthorizeAttribute)).FirstOrDefault(); if (authAttribute != null && authAttribute.ToString() != "") { string[] roles = authAttribute.Roles.Split(','); foreach (string role in roles) { if (roles.Length == 2) { if (role == "Admin") { if (context.HttpContext.User.IsInRole(role)) { return; } else { continue; } } if (role == "User") { if (context.HttpContext.User.IsInRole(role)) { return; } else { break; } } } else { if (context.HttpContext.User.IsInRole(role)) { return; } else { throw new UnauthorizedAccessException("Unauthorized. Admin access only."); } } } throw new UnauthorizedAccessException("Unauthorized. Check ApiKey in Header is correct."); } } catch (Exception e) { context.HttpContext.Response.StatusCode = 401; context.Result = new JsonResult(e.Message); } }
private string[] ExtractRoles(AuthorizeAttribute customAttr) { if (string.IsNullOrEmpty(customAttr.Roles)) { return(null); } return(customAttr.Roles.Split(',')); }
protected override bool IsAuthorized(HttpActionContext actionContext) { Assembly a = Assembly.Load("Synapse.Server"); Type t = a.GetType("Synapse.Services.SynapseAuthorize", true); AuthorizeAttribute aatt = Activator.CreateInstance(t, "Custom", _topic) as AuthorizeAttribute; MethodInfo isAuthed = t.GetMethod("IsAuthorizedWrapper", new Type[] { typeof(HttpActionContext) }); return((bool)isAuthed.Invoke(aatt, new object[] { actionContext })); }
public void AuthorizeAttributeReturnsUniqueTypeIDs() { // Arrange AuthorizeAttribute attr1 = new AuthorizeAttribute(); AuthorizeAttribute attr2 = new AuthorizeAttribute(); // Assert Assert.NotEqual(attr1.TypeId, attr2.TypeId); }
public void UpdateUserAsync_should_have_authorize_attribute() { // Assert Type controllerType = typeof(UserController); MethodBase methodBase = controllerType.GetMethod(nameof(_userController.UpdateUserAsync)); AuthorizeAttribute authorizeAttribute = methodBase.GetCustomAttribute <AuthorizeAttribute>(); Assert.IsTrue(authorizeAttribute != null); }
public void OnAuthorizationThrowsIfFilterContextIsNull() { // Arrange AuthorizeAttribute attr = new AuthorizeAttribute(); // Act & assert Assert.ThrowsArgumentNull( delegate { attr.OnAuthorization(null); }, "filterContext"); }
public void Test_GetAttribute_ReturnsValue() { var parameterAttribute = new AuthorizeAttribute("parameter"); var parameterMock = GetParameterModelMock(new List <object> { parameterAttribute }); Utils.GetAttribute <AuthorizeAttribute>(parameterMock.Object).Should().Be(parameterAttribute); }
public void Test_GetAttributeTransitive_ReturnsActionAttribute() { var actionAttribute = new AuthorizeAttribute("action"); var actionMock = GetActionModelMock(new List <object> { actionAttribute }, new List <object> { }); Utils.GetAttributeTransitive <AuthorizeAttribute>(actionMock.Object).Should().Be(actionAttribute); }
public void AddUserAsync_should_have_authorize_attribute_with_role_admin() { // Assert Type controllerType = typeof(UserController); MethodBase methodBase = controllerType.GetMethod(nameof(_userController.AddUserAsync)); AuthorizeAttribute authorizeAttribute = methodBase.GetCustomAttribute <AuthorizeAttribute>(); Assert.IsTrue(authorizeAttribute != null); Assert.IsTrue(authorizeAttribute.Roles.Contains("Admin")); }
public void Test_GetAttributeTransitive_ReturnsControllerAttribute() { var controllerAttribute = new AuthorizeAttribute("controller"); var actionMock = GetActionModelMock(new List <object> { }, new List <object> { controllerAttribute }); Utils.GetAttributeTransitive <AuthorizeAttribute>(actionMock.Object).Should().Be(controllerAttribute); }
public When_Home_Controller_SaveServiceStatusHistory_Authorize_Attribute() { const BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; var methodInfos = typeof(HomeController) .GetMember(nameof(HomeController.SaveServiceStatusHistoryAsync), MemberTypes.Method, flags) .Cast <MethodInfo>().ToList(); _authorizeAttribute = methodInfos[0].GetCustomAttribute <AuthorizeAttribute>(); }
/// <summary> /// Requiring Authentication adds an <see cref="AuthorizeModule"/> to the <see cref="IHubPipeline" /> with <see cref="IAuthorizeHubConnection"/> /// and <see cref="IAuthorizeHubMethodInvocation"/> authorizers that will be applied globally to all hubs and hub methods. /// These authorizers require that the <see cref="System.Security.Principal.IPrincipal"/>'s <see cref="System.Security.Principal.IIdentity"/> /// IsAuthenticated for any clients that invoke server-side hub methods or receive client-side hub method invocations. /// </summary> /// <param name="pipeline">The <see cref="IHubPipeline" /> to which the <see cref="AuthorizeModule" /> will be added.</param> public static void RequireAuthentication(this IHubPipeline pipeline) { if (pipeline == null) { throw new ArgumentNullException("pipeline"); } var authorizer = new AuthorizeAttribute(); pipeline.AddModule(new AuthorizeModule(globalConnectionAuthorizer: authorizer, globalInvocationAuthorizer: authorizer)); }
public static async Task <bool> AssertAuthorized(this AuthorizeAttribute attribute, IAuthorizationService authService, ClaimsPrincipal user) { var authorize = await authService.AuthorizeAsync(user, attribute.Policy); if (authorize.Succeeded) { return(true); } return(false); }
public void AllowRequest_Does_Not_Set_Status_If_Request_Is_Accepted() { var attr = new AuthorizeAttribute(); AddUser("any"); attr.AllowRequest(_Environment.Environment); Assert.AreEqual(null, _Environment.ResponseStatusCode); }
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); var authorizeAttribute = new AuthorizeAttribute() { Roles = "infovisionlabs\\sigmaflow" }; filters.Add(authorizeAttribute); }
/// <summary> /// Requiring Authentication adds an <see cref="AuthorizeModule"/> to the <see cref="HubOptions" /> with <see cref="IAuthorizeHubConnection"/> /// and <see cref="IAuthorizeHubMethodInvocation"/> authorizers that will be applied globally to all hubs and hub methods. /// These authorizers require that the <see cref="System.Security.Principal.IPrincipal"/>'s <see cref="System.Security.Principal.IIdentity"/> /// IsAuthenticated for any clients that invoke server-side hub methods or receive client-side hub method invocations. /// </summary> /// <param name="options">The <see cref="HubOptions" /> to which the <see cref="AuthorizeModule" /> will be added.</param> public static void RequireAuthentication(this HubOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } var authorizer = new AuthorizeAttribute(); options.PipelineModules.Add(new AuthorizeModule(globalConnectionAuthorizer: authorizer, globalInvocationAuthorizer: authorizer)); }
public void Test_GetAttribute_ThrowsOnMultipmeAttributes() { var parameterAttribute = new AuthorizeAttribute("parameter"); var parameterMock = GetParameterModelMock(new List <object> { parameterAttribute, parameterAttribute }); Action action = () => Utils.GetAttribute <AuthorizeAttribute>(parameterMock.Object); action.Should().Throw <InvalidOperationException>(); }
public void AuthedAsWrongRoles_IsAuthorized_False() { var attribute = new AuthorizeAttribute { Users = "Bob", Roles = "MyRole,OtherRole" }; bool authorised = attribute.IsAuthorized(new TestRestUser { Username = "******" }); Assert.False(authorised); }
protected virtual bool VerifyAuthorizeAttribute(AuthorizeAttribute authorizeAttribute, ControllerContext controllerContext, ActionDescriptor actionDescriptor) { var authorizationContext = this.mvcContextFactory.CreateAuthorizationContext(controllerContext, actionDescriptor); authorizeAttribute.OnAuthorization(authorizationContext); if (authorizationContext.Result != null) { return(false); } return(true); }
public static bool IsAccessibleToUser(string actionToAuthorize, string controllerToAuthorize, HttpContext context) { IPrincipal principal = context.User; //cache the attribute list for both controller class and it's methods ArrayList controllerAttributes = GetControllerAttributes(controllerToAuthorize, context); ArrayList actionAttributes = GetMethodAttributes(controllerToAuthorize, actionToAuthorize, context); if (controllerAttributes.Count == 0 && actionAttributes.Count == 0) { return(true); } string roles = ""; string users = ""; if (controllerAttributes.Count > 0) { AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute; roles += attribute.Roles; users += attribute.Users; } if (actionAttributes.Count > 0) { AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute; roles += attribute.Roles; users += attribute.Users; } if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated) { return(true); } string[] roleArray = roles.Split(','); string[] usersArray = users.Split(','); foreach (string role in roleArray) { if (role == "*" || principal.IsInRole(role)) { return(true); } } foreach (string user in usersArray) { if (user == "*" && (principal.Identity.Name == user)) { return(true); } } return(false); }
public void Constructor_ParamsRoles_ParsedCorrectly() { // Act var attr = new AuthorizeAttribute("User", "Admin"); // Assert Assert.AreEqual(2, attr.RequiredUserRoles.Count()); Assert.IsTrue(attr.RequiredUserRoles.Contains("Admin")); Assert.IsTrue(attr.RequiredUserRoles.Contains("User")); }
public void OnAuthorizationThrowsIfFilterContextIsNull() { // Arrange AuthorizeAttribute attr = new AuthorizeAttribute(); // Act & assert ExceptionHelper.ExpectArgumentNullException( delegate { attr.OnAuthorization(null); }, "filterContext"); }
public void AuthedAsRightName_IsAuthorized_True() { var attribute = new AuthorizeAttribute { Users = "Bill" }; bool authorised = attribute.IsAuthorized(new TestRestUser { Username = "******" }); Assert.True(authorised); }
public void OnAuthorization(AuthorizationFilterContext context) { try { AuthorizeAttribute authAttribute = (AuthorizeAttribute)context.ActionDescriptor.EndpointMetadata.Where(e => e.GetType() == typeof(AuthorizeAttribute)).FirstOrDefault(); if (authAttribute != null) { string[] roles = authAttribute.Roles.Split(','); int i = 0; foreach (string role in roles) { i += 1; //Admin permission if (roles.Length <= 1) { if (context.HttpContext.User.IsInRole(role)) { return; } else { context.HttpContext.Response.StatusCode = 401; context.Result = new JsonResult("Unauthorized. Admin access only."); } } else { // User or Admin permission if (context.HttpContext.User.IsInRole(role)) { return; } //If its less than 2 we dont want to send a message yet //There are still some more roles to check else if (i < 2) { continue; } else { context.HttpContext.Response.StatusCode = 401; context.Result = new JsonResult("Unauthorized."); } } } } } catch { context.HttpContext.Response.StatusCode = 401; context.Result = new JsonResult("Unauthorized. Check ApiKey in Header is correct."); } }
public void AuthedAsWrongName_IsAuthorized_False() { var attribute = new AuthorizeAttribute { Users = "Fred" }; bool authorised = attribute.IsAuthorized(new TestRestUser { Username = "******" }); Assert.False(authorised); }
public void AuthedAsRightRoleWrongUser_IsAuthorized_False() { var attribute = new AuthorizeAttribute { Users = "Bob", Roles = "TestRole" }; bool authorised = attribute.IsAuthorized(new TestRestUser { Username = "******" }); Assert.False(authorised); }
public async Task Invoke_EmptyClaimsShouldAuthorizeAuthenticatedUser() { // Arrange var authorizationService = new DefaultAuthorizationService(Enumerable.Empty<IAuthorizationPolicy>()); var authorizeAttribute = new AuthorizeAttribute(); var authorizationContext = GetAuthorizationContext(services => services.AddInstance<IAuthorizationService>(authorizationService) ); // Act await authorizeAttribute.OnAuthorizationAsync(authorizationContext); // Assert Assert.Null(authorizationContext.Result); }
public async Task Invoke_ValidClaimShouldNotFail() { // Arrange var authorizationService = new DefaultAuthorizationService(Enumerable.Empty<IAuthorizationPolicy>()); var authorizeAttribute = new AuthorizeAttribute("Permission", "CanViewPage"); var authorizationContext = GetAuthorizationContext(services => services.AddInstance<IAuthorizationService>(authorizationService) ); // Act await authorizeAttribute.OnAuthorizationAsync(authorizationContext); // Assert Assert.Null(authorizationContext.Result); }
public async Task Invoke_EmptyClaimsWithAllowAnonymousAttributeShouldNotRejectAnonymousUser() { // Arrange var authorizationService = new DefaultAuthorizationService(Enumerable.Empty<IAuthorizationPolicy>()); var authorizeAttribute = new AuthorizeAttribute(); var authorizationContext = GetAuthorizationContext(services => services.AddInstance<IAuthorizationService>(authorizationService), anonymous: true ); authorizationContext.Filters.Add(new AllowAnonymousAttribute()); // Act await authorizeAttribute.OnAuthorizationAsync(authorizationContext); // Assert Assert.Null(authorizationContext.Result); }
public async Task Invoke_NullPoliciesShouldNotFail() { // Arrange var authorizationService = new DefaultAuthorizationService(policies: null); var authorizeAttribute = new AuthorizeAttribute("Permission", "CanViewPage"); var authorizationContext = GetAuthorizationContext(services => services.AddInstance<IAuthorizationService>(authorizationService) ); // Act await authorizeAttribute.OnAuthorizationAsync(authorizationContext); // Assert Assert.Null(authorizationContext.Result); }
/// <summary> /// Requiring Authentication adds an <see cref="AuthorizeModule"/> to the <see cref="HubOptions" /> with <see cref="IAuthorizeHubConnection"/> /// and <see cref="IAuthorizeHubMethodInvocation"/> authorizers that will be applied globally to all hubs and hub methods. /// These authorizers require that the <see cref="System.Security.Principal.IPrincipal"/>'s <see cref="System.Security.Principal.IIdentity"/> /// IsAuthenticated for any clients that invoke server-side hub methods or receive client-side hub method invocations. /// </summary> /// <param name="options">The <see cref="HubOptions" /> to which the <see cref="AuthorizeModule" /> will be added.</param> public static void RequireAuthentication([NotNull]this HubOptions options) { var authorizer = new AuthorizeAttribute(); options.PipelineModules.Add(new AuthorizeModule(globalConnectionAuthorizer: authorizer, globalInvocationAuthorizer: authorizer)); }
public static void RequireAuthentication(this IHubPipeline pipeline) { var authorizer = new AuthorizeAttribute(); pipeline.AddModule(new AuthorizeModule(globalConnectionAuthorizer: authorizer, globalInvocationAuthorizer: authorizer)); }
public async Task Invoke_FailedContextShouldNotCheckPermission() { // Arrange bool authorizationServiceIsCalled = false; var authorizationService = new Mock<IAuthorizationService>(); authorizationService .Setup(x => x.AuthorizeAsync(Enumerable.Empty<Claim>(), null, null)) .Returns(() => { authorizationServiceIsCalled = true; return Task.FromResult(true); }); var authorizeAttribute = new AuthorizeAttribute("Permission", "CanViewComment"); var authorizationContext = GetAuthorizationContext(services => services.AddInstance<IAuthorizationService>(authorizationService.Object) ); authorizationContext.Result = new HttpStatusCodeResult(401); // Act await authorizeAttribute.OnAuthorizationAsync(authorizationContext); // Assert Assert.False(authorizationServiceIsCalled); }
protected BaseDescription(MemberInfo m) { this.OutputCache = m.GetMyAttribute<OutputCacheAttribute>(); this.SessionMode = m.GetMyAttribute<SessionModeAttribute>(); this.Authorize = m.GetMyAttribute<AuthorizeAttribute>(true /* inherit */); }