public Task <AuthorizationPolicy> GetPolicyAsync(string policyName)
        {
            if (policyName.StartsWith("Permission", StringComparison.OrdinalIgnoreCase))
            {
                var policy = new AuthorizationPolicyBuilder();
                policy.AddRequirements(new PermissionRequirement(policyName));
                return(Task.FromResult(policy.Build()));
            }

            return(FallbackPolicyProvider.GetPolicyAsync(policyName));
        }
コード例 #2
0
 public static void ConfigureAuthorization(this IServiceCollection services)
 {
     services.AddAuthorization(options =>
     {
         var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder("AzureAdB2C",
                                                                                "AzureAd");
         defaultAuthorizationPolicyBuilder =
             defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
         options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
     });
 }
コード例 #3
0
        public AuthorizationPolicy Build(HttpContext httpContext)
        {
            AuthorizationPolicyBuilder authorizationPolicyBuilder = new AuthorizationPolicyBuilder();

            authorizationPolicyBuilder.RequireAssertion(async context =>
            {
                return(await context.User.HasClaimAsync(httpContext, x => x.Type == Name));
            });

            return(authorizationPolicyBuilder.Build());
        }
コード例 #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => options.UseConfiguredCors(Configuration.GetSection("CorsPolicy")));
            services.AddSignalR()
            .AddJsonProtocol(options =>
            {
                options.PayloadSerializerSettings.Converters.Add(new StringEnumConverter());
            });
            services.AddMvc(options =>
            {
                // Require all scopes in authOptions
                var policyBuilder = new AuthorizationPolicyBuilder().RequireAuthenticatedUser();
                Array.ForEach(_authOptions.AuthorizationScope.Split(' '), x => policyBuilder.RequireScope(x));

                var policy = policyBuilder.Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
            // allow upload of large files
            services.Configure <FormOptions>(x => {
                x.ValueLengthLimit         = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue;
            });
            services.Configure <VmOptions>(Configuration.GetSection("VMOptions"));
            services.Configure <RewriteHostOptions>(Configuration.GetSection("RewriteHost"));

            services.AddScoped <VmService>();

            services.AddSingleton <ConnectionService>();
            services.AddSingleton <IHostedService>(x => x.GetService <ConnectionService>());
            services.AddSingleton <IConnectionService>(x => x.GetService <ConnectionService>());

            services.AddSingleton <TaskService>();
            services.AddSingleton <IHostedService>(x => x.GetService <TaskService>());

            services.AddSwagger(_authOptions);

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority                 = _authOptions.Authority;
                options.RequireHttpsMetadata      = _authOptions.RequireHttpsMetadata;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidAudiences = _authOptions.AuthorizationScope.Split(' ')
                };
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <IPrincipal>(p => p.GetService <IHttpContextAccessor>().HttpContext.User);
        }
コード例 #5
0
ファイル: TokenPolicy.cs プロジェクト: ywainmartin/Gateway
 public Task <AuthorizationPolicy> GetPolicyAsync(string policyName)
 {
     string[] subStringPolicy = policyName.Split(new char[] { '.' });
     if (subStringPolicy.Length > 1 && subStringPolicy[0].Equals("Token", StringComparison.OrdinalIgnoreCase) && int.TryParse(subStringPolicy[1], out var token))
     {
         var policy = new AuthorizationPolicyBuilder();
         policy.AddRequirements(new TokenAuthRequirement(token));
         return(Task.FromResult(policy.Build()));
     }
     return(DefaultPolicyProvider.GetPolicyAsync(policyName));
 }
コード例 #6
0
        /// <summary>
        /// Returns a concrete policy from a builder
        /// </summary>
        /// <param name="configurePolicy"></param>
        /// <returns></returns>
        private static AuthorizationPolicy GetPolicy(Action <AuthorizationPolicyBuilder> configurePolicy)
        {
            if (configurePolicy == null)
            {
                throw new ArgumentNullException(nameof(configurePolicy));
            }
            var authorizationPolicyBuilder = new AuthorizationPolicyBuilder();

            configurePolicy(authorizationPolicyBuilder);
            return(authorizationPolicyBuilder.Build());
        }
コード例 #7
0
 // Policies are looked up by string name, so expect 'parameters' (like age)
 // to be embedded in the policy names. This is abstracted away from developers
 // by the more strongly-typed attributes derived from AuthorizeAttribute
 // (like [MinimumAgeAuthorize()] in this sample)
 public Task <AuthorizationPolicy> GetPolicyAsync(string policyName)
 {
     if (policyName.StartsWith(POLICY_PREFIX, StringComparison.OrdinalIgnoreCase) &&
         int.TryParse(policyName.Substring(POLICY_PREFIX.Length), out var age))
     {
         var policy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme);
         policy.AddRequirements(new AgeRequirement(age));
         return(Task.FromResult(policy.Build()));
     }
     return(Task.FromResult <AuthorizationPolicy>(null));
 }
コード例 #8
0
    public override Task <AuthorizationPolicy> GetPolicyAsync(string policyName)
    {
        var builder = new AuthorizationPolicyBuilder();

        builder.RequireAuthenticatedUser()
        .RequireClaim(Consts.PrivilegeClaimType, policyName)
        .AddAuthenticationSchemes(
            JwtBearerDefaults.AuthenticationScheme,
            TokenOptions.DefaultSchemaName
            );
        return(Task.FromResult(builder.Build()));
    }
コード例 #9
0
 public override Task <AuthorizationPolicy> GetPolicyAsync(string policyName)
 {
     if (policyName.StartsWith("Claim_", StringComparison.InvariantCultureIgnoreCase))
     {
         var builder   = new AuthorizationPolicyBuilder();
         var claimName = policyName.Substring(6);
         builder.RequireClaim(claimName, "1", "true");
         var policy = builder.Build();
         return(Task.FromResult(policy));
     }
     return(base.GetPolicyAsync(policyName));
 }
コード例 #10
0
        public static void WithPolicy(
            this IProvideMetadata type,
            Action <AuthorizationPolicyBuilder> policy)
        {
            var policyBuilder = new AuthorizationPolicyBuilder();

            policy.Invoke(policyBuilder);

            var authorizationPolicy = type.GetMetadata(PolicyKey, policyBuilder.Build());

            type.Metadata[PolicyKey] = authorizationPolicy;
        }
コード例 #11
0
        // Dynamically creates a policy with a requirement that contains the permission.
        // The policy name must match the permission that is needed.
        public Task <AuthorizationPolicy> GetPolicyAsync(string policyName)
        {
            if (policyName.StartsWith("Grant", StringComparison.OrdinalIgnoreCase))
            {
                var policy = new AuthorizationPolicyBuilder();
                policy.AddRequirements(new GrantRequirement(policyName));
                return(Task.FromResult(policy.Build()));
            }

            // Policy is not for permissions, try the default provider.
            return(FallbackPolicyProvider.GetPolicyAsync(policyName));
        }
コード例 #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext <MovieShopDbContext>(
                options => options.UseSqlServer
                    (Configuration.GetConnectionString("MovieShopDbConnection")));

            services.AddAutoMapper(typeof(Startup), typeof(MoviesMappingProfile));
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            //register repositories
            services.AddScoped <IAsyncRepository <Genre>, EfRepository <Genre> >();
            services.AddScoped <IMovieRepository, MovieRepository>();
            services.AddScoped <IAsyncRepository <Cast>, EfRepository <Cast> >();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IPurchaseRepository, PurchaseRepository>();
            services.AddScoped <IFavoriteRepository, FavoriteRepository>();
            services.AddScoped <IAsyncRepository <Review>, EfRepository <Review> >();
            services.AddScoped <ICastRepository, CastRepository>();
            services.AddScoped <IGenreRepository, GenreRepository>();

            //register services
            services.AddScoped <IGenreService, GenreService>();
            services.AddScoped <IMovieService, MovieService>();
            services.AddScoped <ICastService, CastService>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <ICryptoService, CryptoService>();
            services.AddScoped <ICurrentUserService, CurrentUserService>();
            //services.AddAutoMapper<typeof(Startup), typeof(MoviesMappingProfile));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         =
                        new SymmetricSecurityKey(Encoding
                                                 .UTF8
                                                 .GetBytes(Configuration
                                                           ["TokenSettings:PrivateKey"]))
                };
            });
            services.AddAuthorization(options =>
            {
                var defaultAuthorizationPolicyBuilder =
                    new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme);
                defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
                options.DefaultPolicy             = defaultAuthorizationPolicyBuilder.Build();
            });
        }
コード例 #13
0
        public Task <AuthorizationPolicy> GetPolicyAsync(string policyName)
        {
            string[] subStringPolicy = policyName.Split(new char[] { '.' });

            if (subStringPolicy.Length > 1 && subStringPolicy[0].Equals("Role", StringComparison.OrdinalIgnoreCase) && Enum.TryParse(typeof(Role), subStringPolicy[1], false, out var role))
            {
                var policy = new AuthorizationPolicyBuilder();
                policy.AddRequirements(new SecureRequirement((Role)role));
                return(Task.FromResult(policy.Build()));
            }
            return(defaultPolicyProvider.GetPolicyAsync(policyName));
        }
コード例 #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "MovieShop API", Version = "v1"
                });
            });

            services.AddMvc(options => { options.Filters.Add(typeof(ModelStateValidationFilterAttribute)); });

            // Add memory cache services
            services.AddMemoryCache();
            services.AddHttpContextAccessor();

            services.AddDbContext <MovieShopDbContext>(options =>
                                                       options.UseSqlServer(Configuration
                                                                            .GetConnectionString("MovieShopDbConnection")));
            services.AddAutoMapper(typeof(Startup), typeof(MoviesMappingProfile));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         =
                        new SymmetricSecurityKey(Encoding
                                                 .UTF8
                                                 .GetBytes(Configuration
                                                           ["TokenSettings:PrivateKey"]))
                };
            });

            services.AddAuthorization(options =>
            {
                var defaultAuthorizationPolicyBuilder =
                    new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme);
                defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
                options.DefaultPolicy             = defaultAuthorizationPolicyBuilder.Build();
            });

            ConfigureRepositoriesDependencyInjection(services);
            ConfigureServicesDependencyInjection(services);
        }
コード例 #15
0
        public Task <AuthorizationPolicy> GetPolicyAsync(string policyName)
        {
            if (policyName == POLICY)
            {
                var policy = new AuthorizationPolicyBuilder();
                policy.AddRequirements(new RoleBaseRequirement {
                });
                return(Task.FromResult(policy.Build()));
            }

            return(FallbackPolicyProvider.GetPolicyAsync(policyName));
        }
コード例 #16
0
        public Task <AuthorizationPolicy> GetPolicyAsync(string policyName)
        {
            if (policyName.StartsWith(POLICY_PREFIX, StringComparison.OrdinalIgnoreCase))
            {
                var policy = new AuthorizationPolicyBuilder();
                var valor  = policyName.Substring(POLICY_PREFIX.Length);
                policy.AddRequirements(new PermissaoPolicyRequeriment(valor));
                return(Task.FromResult(policy.Build()));
            }

            return(Task.FromResult <AuthorizationPolicy>(null));
        }
コード例 #17
0
        public Task <AuthorizationPolicy> GetPolicyAsync(string policyName)
        {
            if (policyName.StartsWith(InfrastructureConstants.POLICY_PREFIX, StringComparison.OrdinalIgnoreCase) &&
                int.TryParse(policyName.Substring(InfrastructureConstants.POLICY_PREFIX.Length), out var accessLevel))
            {
                var policy = new AuthorizationPolicyBuilder();
                policy.AddRequirements(new MinimumAccessLevelRequirement(accessLevel));
                return(Task.FromResult(policy.Build()));
            }

            return(Task.FromResult <AuthorizationPolicy>(null));
        }