예제 #1
0
        /// <summary>
        /// Adds a <see cref="AuthorizeFilter"/> with the specified policy to all pages under the specified folder.
        /// </summary>
        /// <param name="conventions">The <see cref="PageConventionCollection"/> to configure.</param>
        /// <param name="areaName">The area name.</param>
        /// <param name="folderPath">
        /// The folder path e.g. <c>/Manage/</c>
        /// <para>
        /// The folder path is the path of the folder, relative to the pages root directory for the specified area.
        /// e.g. the folder path for the file Areas/Identity/Pages/Manage/Accounts.cshtml, is <c>/Manage</c>.
        /// </para>
        /// </param>
        /// <param name="policy">The authorization policy.</param>
        /// <returns>The <see cref="PageConventionCollection"/>.</returns>
        public static PageConventionCollection AuthorizeAreaFolder(
            this PageConventionCollection conventions,
            string areaName,
            string folderPath,
            string policy)
        {
            if (conventions == null)
            {
                throw new ArgumentNullException(nameof(conventions));
            }

            if (string.IsNullOrEmpty(areaName))
            {
                throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(areaName));
            }

            if (string.IsNullOrEmpty(folderPath))
            {
                throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(folderPath));
            }

            var authorizeFilter = new AuthorizeFilter(policy);

            conventions.AddAreaFolderApplicationModelConvention(areaName, folderPath, model => model.Filters.Add(authorizeFilter));
            return(conventions);
        }
        public async Task CombinedAuthorizeFilter_AlwaysCalledWithNonDefaultProvider()
        {
            // Arrange
            var applicationModelProviderContext = GetProviderContext(typeof(AuthorizeController));

            var policyProvider = new TestAuthorizationPolicyProvider();

            var controller      = Assert.Single(applicationModelProviderContext.Result.Controllers);
            var action          = Assert.Single(controller.Actions);
            var authorizeData   = action.Attributes.OfType <AuthorizeAttribute>();
            var authorizeFilter = new AuthorizeFilter(policyProvider, authorizeData);

            var actionContext = new ActionContext(GetHttpContext(), new RouteData(), new ControllerActionDescriptor());

            var authorizationFilterContext = new AuthorizationFilterContext(actionContext, action.Filters);

            authorizationFilterContext.Filters.Add(authorizeFilter);

            var secondFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAssertion(a => true).Build());

            authorizationFilterContext.Filters.Add(secondFilter);

            var thirdFilter = new AuthorizeFilter(policyProvider, authorizeData);

            authorizationFilterContext.Filters.Add(thirdFilter);

            // Act
            await thirdFilter.OnAuthorizationAsync(authorizationFilterContext);

            await thirdFilter.OnAuthorizationAsync(authorizationFilterContext);

            // Assert
            Assert.Equal(4, policyProvider.GetPolicyCount);
        }
예제 #3
0
        public async Task Invoke_FailedContextShouldNotCheckPermission()
        {
            // Arrange
            bool authorizationServiceIsCalled = false;
            var  authorizationService         = new Mock <IAuthorizationService>();

            authorizationService
            .Setup(x => x.AuthorizeAsync(null, null, "CanViewComment"))
            .Returns(() =>
            {
                authorizationServiceIsCalled = true;
                return(Task.FromResult(true));
            });

            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder()
                                                      .RequireClaim("Permission", "CanViewComment")
                                                      .Build());
            var authorizationContext = GetAuthorizationContext(services =>
                                                               services.AddInstance(authorizationService.Object)
                                                               );

            authorizationContext.Result = new HttpUnauthorizedResult();

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.False(authorizationServiceIsCalled);
        }
예제 #4
0
        public void OnProvidersExecuting_CollatesAttributesFromInheritedTypes()
        {
            // Arrange
            var options = Options.Create(new AuthorizationOptions());

            options.Value.AddPolicy("Base", policy => policy.RequireClaim("Basic").RequireClaim("Basic2"));
            options.Value.AddPolicy("Derived", policy => policy.RequireClaim("Derived"));

            var policyProvider        = new DefaultAuthorizationPolicyProvider(options);
            var authorizationProvider = new AuthorizationPageApplicationModelProvider(policyProvider);

            var context = GetApplicationProviderContext(typeof(TestPageWithDerivedModel).GetTypeInfo());

            // Act
            authorizationProvider.OnProvidersExecuting(context);

            // Assert
            AuthorizeFilter authorizeFilter = null;

            Assert.Collection(
                context.PageApplicationModel.Filters,
                f => Assert.IsType <PageHandlerPageFilter>(f),
                f => Assert.IsType <HandleOptionsRequestsPageFilter>(f),
                f => authorizeFilter = Assert.IsType <AuthorizeFilter>(f));

            // Basic + Basic2 + Derived authorize
            Assert.Equal(3, authorizeFilter.Policy.Requirements.Count);
        }
예제 #5
0
    public async Task AuthorizationFilterCombinesMultipleFiltersWithPolicyProvider()
    {
        // Arrange
        var authorizeFilter = new AuthorizeFilter(new TestPolicyProvider(), new IAuthorizeData[]
        {
            new AuthorizeAttribute {
                Policy = "true"
            },
            new AuthorizeAttribute {
                Policy = "false"
            }
        });
        var authorizationContext = GetAuthorizationContext(anonymous: false);

        // Effective policy should fail, if both are combined
        authorizationContext.Filters.Add(authorizeFilter);
        var secondFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAssertion(a => true).Build());

        authorizationContext.Filters.Add(secondFilter);

        // Act
        await secondFilter.OnAuthorizationAsync(authorizationContext);

        // Assert
        Assert.IsType <ForbidResult>(authorizationContext.Result);
    }
예제 #6
0
    public async Task GetEffectivePolicyAsync_CombinesPoliciesFromEndpoint()
    {
        // Arrange
        var policy1 = new AuthorizationPolicyBuilder()
                      .RequireClaim("Claim1")
                      .Build();

        var policy2 = new AuthorizationPolicyBuilder()
                      .RequireClaim("Claim2")
                      .Build();

        var filter  = new AuthorizeFilter(policy1);
        var options = new AuthorizationOptions();

        options.AddPolicy("policy2", policy2);
        var policyProvider = new DefaultAuthorizationPolicyProvider(Options.Create(options));

        ActionContext.HttpContext.RequestServices = new ServiceCollection()
                                                    .AddSingleton <IAuthorizationPolicyProvider>(policyProvider)
                                                    .BuildServiceProvider();

        ActionContext.HttpContext.SetEndpoint(new Endpoint(
                                                  _ => null,
                                                  new EndpointMetadataCollection(new AuthorizeAttribute("policy2")),
                                                  "test"));
        var context = new AuthorizationFilterContext(ActionContext, new[] { filter, });

        // Act
        var effectivePolicy = await filter.GetEffectivePolicyAsync(context);

        // Assert
        Assert.NotSame(policy1, effectivePolicy);
        Assert.NotSame(policy2, effectivePolicy);
        Assert.Equal(new[] { "Claim1", "Claim2" }, effectivePolicy.Requirements.Cast <ClaimsAuthorizationRequirement>().Select(c => c.ClaimType));
    }
예제 #7
0
        public async Task AuthorizeFilter_CalledTwiceWithDefaultProvider()
        {
            // Arrange
            var applicationModelProviderContext = GetProviderContext(typeof(AuthorizeController));

            var policy          = new AuthorizationPolicyBuilder().RequireAssertion(_ => true).Build();
            var policyProvider  = new Mock <DefaultAuthorizationPolicyProvider>(Options.Create <AuthorizationOptions>(new AuthorizationOptions()));
            var getPolicyCalled = 0;

            policyProvider.Setup(p => p.GetPolicyAsync(It.IsAny <string>())).Callback(() => getPolicyCalled++).ReturnsAsync(policy);

            var controller      = Assert.Single(applicationModelProviderContext.Result.Controllers);
            var action          = Assert.Single(controller.Actions);
            var authorizeData   = action.Attributes.OfType <AuthorizeAttribute>();
            var authorizeFilter = new AuthorizeFilter(policyProvider.Object, authorizeData);

            var actionContext = new ActionContext(GetHttpContext(), new RouteData(), new ControllerActionDescriptor());

            var authorizationFilterContext = new AuthorizationFilterContext(actionContext, new[] { authorizeFilter });

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationFilterContext);

            await authorizeFilter.OnAuthorizationAsync(authorizationFilterContext);

            // Assert
            Assert.Equal(2, getPolicyCalled);
        }
        public static void RequireAuthenticatedUser(this MvcOptions mvcOptions)
        {
            var authorizationPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
            var authorizeFilter     = new AuthorizeFilter(authorizationPolicy);

            mvcOptions.Filters.Add(authorizeFilter);
        }
예제 #9
0
        public void OnActionExecuting_UnauthorizedResult()
        {
            // Arrange

            var filter = new AuthorizeFilter();

            Controller = new CustomerController(null)
            {
                AccountService = AccountService,

                AccountTicket = null
            };

            var actionExecutingContext =
                MockHelper.ActionExecutingContext(Controller);

            // Act

            filter.OnActionExecuting(actionExecutingContext);

            // Assert

            Assert.IsNotNull(actionExecutingContext.Result);

            Assert.IsInstanceOf <UnauthorizedResult>
                (actionExecutingContext.Result);
        }
예제 #10
0
    public async Task AuthorizeFilterWillCallPolicyProviderOnAuthorization()
    {
        // Arrange
        var policyProvider = new Mock <IAuthorizationPolicyProvider>();
        var getPolicyCount = 0;

        policyProvider.Setup(p => p.GetPolicyAsync(It.IsAny <string>())).ReturnsAsync(new AuthorizationPolicyBuilder().RequireAssertion(_ => true).Build())
        .Callback(() => getPolicyCount++);
        var authorizeFilter      = new AuthorizeFilter(policyProvider.Object, new AuthorizeAttribute[] { new AuthorizeAttribute("whatever") });
        var authorizationContext = GetAuthorizationContext();

        authorizationContext.Filters.Add(authorizeFilter);

        // Act & Assert
        await authorizeFilter.OnAuthorizationAsync(authorizationContext);

        Assert.Equal(1, getPolicyCount);
        Assert.Null(authorizationContext.Result);

        await authorizeFilter.OnAuthorizationAsync(authorizationContext);

        Assert.Equal(2, getPolicyCount);
        Assert.Null(authorizationContext.Result);

        await authorizeFilter.OnAuthorizationAsync(authorizationContext);

        Assert.Equal(3, getPolicyCount);
        Assert.Null(authorizationContext.Result);

        // Make sure we don't cache the policy
        Assert.Null(authorizeFilter.Policy);
    }
예제 #11
0
        public async Task AuthorizeFilter_CalledTwiceWithNonDefaultProvider()
        {
            // Arrange
            var applicationModelProviderContext = new ApplicationModelProviderContext(
                new[] { typeof(AuthorizeController).GetTypeInfo() });

            var policyProvider  = new TestAuthorizationPolicyProvider();
            var defaultProvider = new DefaultApplicationModelProvider(Options.Create(new MvcOptions()));

            defaultProvider.OnProvidersExecuting(applicationModelProviderContext);

            var controller      = Assert.Single(applicationModelProviderContext.Result.Controllers);
            var action          = Assert.Single(controller.Actions);
            var authorizeData   = action.Attributes.OfType <AuthorizeAttribute>();
            var authorizeFilter = new AuthorizeFilter(policyProvider, authorizeData);

            var actionContext = new ActionContext(GetHttpContext(), new RouteData(), new ControllerActionDescriptor());

            var authorizationFilterContext = new AuthorizationFilterContext(actionContext, action.Filters);

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationFilterContext);

            await authorizeFilter.OnAuthorizationAsync(authorizationFilterContext);

            // Assert
            Assert.Equal(2, policyProvider.GetPolicyCount);
        }
예제 #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <ICustomAuthenticationService, MyDbAuthenticationService>();

            services
            .AddMyDbAuthorization()                 // ==> Adds the Policy, Scheme and custom authentication using a ICustomAuthenticationService
            .AddAzureAdAuthorization(Configuration) // ==> Adds the Policy, custom Bearer Scheme using JWT
            .AddMvc()
            .AddFilterProvider((serviceProvider) =>
            {
                var azureAdAuthorizeFilter = new AuthorizeFilter(new AuthorizeData[] { new AuthorizeData {
                                                                                           AuthenticationSchemes = Constants.AzureAdScheme
                                                                                       } });
                var myAuthorizeFilter = new AuthorizeFilter(new AuthorizeData[] { new AuthorizeData {
                                                                                      AuthenticationSchemes = Constants.MyDbScheme
                                                                                  } });

                var filterProviderOptions = new FilterProviderOption[] {
                    new FilterProviderOption {
                        RoutePrefix = "api/users",
                        Filter      = azureAdAuthorizeFilter
                    },
                    new FilterProviderOption {
                        RoutePrefix = "api/data",
                        Filter      = myAuthorizeFilter
                    }
                };

                return(new AuthenticationFilterProvider(filterProviderOptions));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
예제 #13
0
        public MachineApplicationModelConvention(string prefix, IEnumerable <string> authenticationSchemes)
        {
            _prefixRoute = new AttributeRouteModel {
                Template = prefix
            };

            var policyBuilder = new AuthorizationPolicyBuilder(authenticationSchemes.ToArray());

            _authorizeFilter = new AuthorizeFilter(policyBuilder.RequireAuthenticatedUser().Build());
        }
예제 #14
0
        private static AuthorizeFilter GetAuthorizeFilter(ControllerModel controller)
        {
            //var authorizeFilter = controller.ControllerName.Contains("Api")
            //    ? new AuthorizeFilter("api-policy")
            //    : new AuthorizeFilter("default-policy");

            var authorizeFilter = new AuthorizeFilter("api-policy");

            return(authorizeFilter);
        }
예제 #15
0
        /// <summary>
        /// This method gets called by the runtime.
        /// Use this method to add services to the container.
        /// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        /// </summary>
        /// <param name="services">Collection of the services that will be added to the dependency injection container.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(typeof(AutoMapperMappings));

            AuthorizationPolicy authPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
            AuthorizeFilter     authFilter = new AuthorizeFilter(authPolicy);

            services.AddMvc(config => config.Filters.Add(authFilter)).AddXmlSerializerFormatters();

            services.AddAppServices(_config);
        }
예제 #16
0
        public void Test_NotEqual(ModeEnum must, ModeEnum have)
        {
            // Arrange

            // Act

            var result = AuthorizeFilter.Test(must, have);

            // Assert

            Assert.IsFalse(result);
        }
예제 #17
0
        public static MvcOptions AddDefaultAuthorizationPolicyFilter(this MvcOptions options)
        {
            // Default authorization policy enforced via a global authorization filter
            AuthorizationPolicy requireLoginPolicy = new AuthorizationPolicyBuilder()
                                                     .RequireAuthenticatedUser()
                                                     .Build();

            AuthorizeFilter filter = new AuthorizeFilter(requireLoginPolicy);

            options.Filters.Add(filter);
            return(options);
        }
예제 #18
0
        public async Task Invoke_RequireAdminAndUserRoleWithNoPolicyShouldSucceed()
        {
            // Arrange
            var authorizeFilter      = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireRole("Administrator").Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.Null(authorizationContext.Result);
        }
예제 #19
0
        public async Task Invoke_ValidClaimShouldNotFail()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireClaim("Permission", "CanViewPage").Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.Null(authorizationContext.Result);
        }
예제 #20
0
    public async Task AuthorizeFilterCanAuthorizeNullUser()
    {
        // Arrange
        var authorizeFilter      = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAssertion(_ => true).Build());
        var authorizationContext = GetAuthorizationContext(anonymous: true);

        // Act
        await authorizeFilter.OnAuthorizationAsync(authorizationContext);

        // Assert
        Assert.Null(authorizationContext.Result);
    }
예제 #21
0
        public async Task Invoke_EmptyClaimsShouldAuthorizeAuthenticatedUser()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.Null(authorizationContext.Result);
        }
예제 #22
0
 public virtual void ProvideFilter(FilterProviderContext context, FilterItem filterItem)
 {
     if (filterItem.Descriptor.Filter is AuthorizeFilter && (object)filterItem.Filter == null)
     {
         AuthorizeFilter val = filterItem.Descriptor.Filter as AuthorizeFilter;
         IEnumerable <IAuthorizeData> enumerable = val.AuthorizeData;
         if (enumerable == null && (object)val.Policy != null)
         {
             List <IAuthorizeData> list = new List <IAuthorizeData>();
             string text = val.Policy.AuthenticationSchemes.FirstOrDefault();
             if (!string.IsNullOrEmpty(text))
             {
                 List <IAuthorizeData> list2 = list;
                 MvcAuthorizeAttribute mvcAuthorizeAttribute = new MvcAuthorizeAttribute();
                 mvcAuthorizeAttribute.AuthenticationSchemes = text;
                 list2.Add(mvcAuthorizeAttribute);
             }
             enumerable = list;
         }
         filterItem.Filter     = new MvcAuthorizeFilter(enumerable).CreateInstance(context.ActionContext.HttpContext.RequestServices);
         filterItem.IsReusable = true;
     }
     if ((object)filterItem.Filter != null)
     {
         AuthorizeFilter    val2;
         MvcAuthorizeFilter mvcAuthorizeFilter = default(MvcAuthorizeFilter);
         if ((val2 = (filterItem.Filter as AuthorizeFilter)) != null && (mvcAuthorizeFilter = (filterItem.Descriptor.Filter as MvcAuthorizeFilter)) != null)
         {
             filterItem.Filter = mvcAuthorizeFilter.CreateInstance(context.ActionContext.HttpContext.RequestServices);
         }
     }
     else
     {
         IFilterMetadata val3 = filterItem.Descriptor.Filter;
         IFilterFactory  val4;
         if ((val4 = (val3 as IFilterFactory)) == null)
         {
             filterItem.Filter     = val3;
             filterItem.IsReusable = true;
         }
         else
         {
             IServiceProvider requestServices = context.ActionContext.HttpContext.RequestServices;
             filterItem.Filter     = val4.CreateInstance(requestServices);
             filterItem.IsReusable = val4.IsReusable;
             if ((object)filterItem.Filter == null)
             {
                 throw new InvalidOperationException("The 'CreateInstance' method of type '" + typeof(IFilterFactory).Name + "' cannot return a null value.");
             }
             ApplyFilterToContainer((object)filterItem.Filter, val4);
         }
     }
 }
예제 #23
0
    public async Task Invoke_EmptyClaimsShouldAuthorizeAuthenticatedUser()
    {
        // Arrange
        var authorizeFilter      = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());
        var authorizationContext = GetAuthorizationContext();

        // Act
        await authorizeFilter.OnAuthorizationAsync(authorizationContext);

        // Assert
        Assert.Null(authorizationContext.Result);
    }
예제 #24
0
        public async Task Invoke_RequireUnknownRoleShouldFail()
        {
            // Arrange
            var authorizeFilter      = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireRole("Wut").Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.NotNull(authorizationContext.Result);
        }
예제 #25
0
        public async Task Invoke_ValidClaimShouldNotFail()
        {
            // Arrange
            var authorizeFilter      = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireClaim("Permission", "CanViewPage").Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.Null(authorizationContext.Result);
        }
예제 #26
0
    public async Task Invoke_SingleValidClaimShouldSucceed()
    {
        // Arrange
        var authorizeFilter      = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireClaim("Permission", "CanViewComment", "CanViewPage").Build());
        var authorizationContext = GetAuthorizationContext();

        // Act
        await authorizeFilter.OnAuthorizationAsync(authorizationContext);

        // Assert
        Assert.Null(authorizationContext.Result);
    }
예제 #27
0
    public async Task AuthZResourceShouldBeAuthorizationFilterContext()
    {
        // Arrange
        var authorizeFilter      = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAssertion(c => c.Resource is AuthorizationFilterContext).Build());
        var authorizationContext = GetAuthorizationContext();

        // Act
        await authorizeFilter.OnAuthorizationAsync(authorizationContext);

        // Assert
        Assert.Null(authorizationContext.Result);
    }
        public void Apply(ControllerModel model)
        {
            var protectedControllers = new[]
            {
                typeof(Level1AtLeastController)
            };

            if (protectedControllers.Contains(model.ControllerType))
            {
                var filter = new AuthorizeFilter();
                model.Filters.Add(filter);
            }
        }
예제 #29
0
        private static void ApplyRestrictions(IScopesEvaluator handler, HttpContext context)
        {
            var requirement = new ODataAuthorizationScopesRequirement(handler);
            var policy      = new AuthorizationPolicyBuilder().AddRequirements(requirement).Build();

            // We use the AuthorizeFilter instead of relying on the built-in authorization middleware
            // because we cannot add new metadata to the endpoint in the middle of a request
            // and OData's current implementation of endpoint routing does not allow for
            // adding metadata to individual routes ahead of time
            var authFilter = new AuthorizeFilter(policy);

            context.ODataFeature().ActionDescriptor?.FilterDescriptors?.Add(new FilterDescriptor(authFilter, 0));
        }
예제 #30
0
파일: Startup.cs 프로젝트: 235u/dimdex
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRouting(options =>
            {
                options.LowercaseUrls         = true;
                options.LowercaseQueryStrings = true;
            });

            services.AddControllersWithViews(config =>
            {
                var builder = new AuthorizationPolicyBuilder();
                AuthorizationPolicy policy = builder.RequireAuthenticatedUser()
                                             .Build();

                var filter = new AuthorizeFilter(policy);
                config.Filters.Add(filter);
            });

            services.AddRazorPages()
            .AddRazorRuntimeCompilation()
            .AddViewOptions(options =>
            {
                options.HtmlHelperOptions.ClientValidationEnabled = false;
            });

            services.AddHsts(options =>
            {
                options.Preload           = true;
                options.IncludeSubDomains = true;
                options.MaxAge            = TimeSpan.FromDays(365);
            });

            services.AddDbContext <ApplicationDbContext>(options =>
            {
                ////options.UseInMemoryDatabase("Dimdex.Organization");
                options.UseSqlite(@"Data Source=.\wwwroot\sqlite.db");
            });

            services.AddIdentity <ApplicationUser, ApplicationRole>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
            });

            services.AddScoped <IUserStore <ApplicationUser>, ApplicationUserStore>();
            services.AddScoped <IUserPasswordStore <ApplicationUser>, ApplicationUserStore>();
            services.AddScoped <IRoleStore <ApplicationRole>, ApplicationRoleStore>();
            services.AddScoped <IUserRoleStore <ApplicationUser>, ApplicationUserStore>();
        }
예제 #31
0
    public void CreateInstance_ReturnsSelfIfPolicyProviderIsSet()
    {
        // Arrange
        var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder()
                                                  .RequireAssertion(_ => true)
                                                  .Build());
        var factory = (IFilterFactory)authorizeFilter;

        // Act
        var result = factory.CreateInstance(new ServiceCollection().BuildServiceProvider());

        // Assert
        Assert.Same(authorizeFilter, result);
    }
예제 #32
0
    public async Task Invoke_RequireUnknownRoleShouldForbid()
    {
        // Arrange
        var authorizeFilter      = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireRole("Wut").Build());
        var authorizationContext = GetAuthorizationContext();

        authorizationContext.Filters.Add(authorizeFilter);

        // Act
        await authorizeFilter.OnAuthorizationAsync(authorizationContext);

        // Assert
        Assert.IsType <ForbidResult>(authorizationContext.Result);
    }
예제 #33
0
        public async Task Invoke_EmptyClaimsWithAllowAnonymousAttributeShouldNotRejectAnonymousUser()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization(),
                anonymous: true);

            authorizationContext.Filters.Add(new AllowAnonymousAttribute());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.Null(authorizationContext.Result);
        }
예제 #34
0
        public async Task Invoke_FailWhenLookingForClaimInOtherIdentity()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder()
                .RequireClaim("Permission", "CanViewComment")
                .Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.NotNull(authorizationContext.Result);
        }
예제 #35
0
        public async Task Invoke_SingleValidClaimShouldSucceed()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireClaim("Permission", "CanViewComment", "CanViewPage").Build());
            var authorizationContext = GetAuthorizationContext(services =>
            {
                services.AddAuthorization();
                services.AddTransient<IAuthorizationHandler, DenyAnonymousAuthorizationHandler>();
            });

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.Null(authorizationContext.Result);
        }
예제 #36
0
        public async Task Invoke_EmptyPolicyWillFail()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder().Build());
            var authorizationContext = GetAuthorizationContext(services =>
            {
                services.AddAuthorization();
                services.AddTransient<IAuthorizationHandler, DenyAnonymousAuthorizationHandler>();
            });

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.NotNull(authorizationContext.Result);
        }
예제 #37
0
        public async Task Invoke_RequireAdminRoleShouldFailWithNoHandlers()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireRole("Administrator").Build());
            var authorizationContext = GetAuthorizationContext(services =>
            {
                services.AddOptions();
                services.AddTransient<IAuthorizationService, DefaultAuthorizationService>();
            });
            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.NotNull(authorizationContext.Result);
        }
예제 #38
0
        public async Task Invoke_RequireAdminAndUserRoleWithNoPolicyShouldSucceed()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireRole("Administrator").Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.Null(authorizationContext.Result);
        }
예제 #39
0
        public async Task Invoke_AuthSchemesFailShouldSetEmptyPrincipalOnContext()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder("Fails")
                .RequireAuthenticatedUser()
                .Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.NotNull(authorizationContext.HttpContext.User?.Identity);
        }
예제 #40
0
        public async Task Invoke_RequireUnknownRoleShouldFail()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireRole("Wut").Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.NotNull(authorizationContext.Result);
        }
예제 #41
0
        public async Task Invoke_RequireAdminRoleButFailPolicyShouldFail()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder()
                .RequireRole("Administrator")
                .RequireClaim("Permission", "CanViewComment")
                .Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.NotNull(authorizationContext.Result);
        }
예제 #42
0
        public async Task Invoke_CanFilterToOnlyBearerScheme()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder("Bearer")
                .RequireClaim("Permission", "CanViewPage")
                .Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.NotNull(authorizationContext.Result);
        }
예제 #43
0
        public async Task Invoke_CanLookingForClaimsInMultipleIdentities()
        {
            // Arrange
            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder("Basic", "Bearer")
                .RequireClaim("Permission", "CanViewComment")
                .RequireClaim("Permission", "CupBearer")
                .Build());
            var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.NotNull(authorizationContext.Result);
        }
예제 #44
0
        public async Task Invoke_FailedContextShouldNotCheckPermission()
        {
            // Arrange
            bool authorizationServiceIsCalled = false;
            var authorizationService = new Mock<IAuthorizationService>();
            authorizationService
                .Setup(x => x.AuthorizeAsync(null, null, "CanViewComment"))
                .Returns(() =>
                {
                    authorizationServiceIsCalled = true;
                    return Task.FromResult(true);
                });

            var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder()
                .RequireClaim("Permission", "CanViewComment")
                .Build());
            var authorizationContext = GetAuthorizationContext(services =>
                services.AddInstance(authorizationService.Object)
                );

            authorizationContext.Result = new HttpUnauthorizedResult();

            // Act
            await authorizeFilter.OnAuthorizationAsync(authorizationContext);

            // Assert
            Assert.False(authorizationServiceIsCalled);
        }