Dependency Injection on Authorization Policy

前端 未结 3 1246
滥情空心
滥情空心 2021-01-19 16:08

I want to create a claim based authorization for my ASP.NET Core app:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthorizat         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-19 16:34

    You can build a service provider using the BuildServiceProvider() method on the IServiceCollection:

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton();
    
            var sp = services.BuildServiceProvider();
            var employeeProvider = sp.GetService();
            string[] values = employeeProvider.GetAuthorizedEmployeeIds();
    
            services.AddAuthorization(options =>
            {
    
                options.AddPolicy("Founders", policy =>
                          policy.RequireClaim("EmployeeNumber", employeeProvider.GetAuthorizedEmployeeIds()));
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
    

    interface and Class

    public interface IEmployeeProvider
    {
        string[] GetAuthorizedEmployeeIds();
    }
    
    public class EmployeeProvider : IEmployeeProvider
    {
        public string[] GetAuthorizedEmployeeIds()
        {
            var data = new string[] { "1", "2", "3", "4", "5" };
            return data;
        }
    }
    

提交回复
热议问题