使用.Net核心Web API在身份服务器4中进行基于角色的授权

时间:2017-05-27 20:35:28

标签: asp.net-web-api asp.net-core oauth-2.0 identityserver4 asp.net-core-webapi

我是.net核心新手。我正在使用身份服务器4进行基于角色的授权。我已经实现了基于角色的授权,它给了我" 500内部服务器错误"当我从authorize属性中删除角色时,它会给我成功的结果。

我的应用程序布局如

  1. 客户端(邮差)
  2. Identity Server4(身份验证服务器)
  3. .Net核心Web API应用程序

  4. Identity Server代码

    配置文件

    public class Config
    {
        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>{
                new ApiResource("dataEventRecords")
                {
                    ApiSecrets =
                    {
                        new Secret("dataEventRecordsSecret".Sha256())
                    },
                    Scopes =
                    {
                        new Scope
                        {
                            Name = "dataeventrecordsscope",
                            DisplayName = "Scope for the dataEventRecords ApiResource"
                        }
                    },
                    UserClaims = { "role", "admin", "user", "dataEventRecords", "dataEventRecords.admin", "dataEventRecords.user" }
                },
                new ApiResource("securedFiles")
                {
                    ApiSecrets =
                    {
                        new Secret("securedFilesSecret".Sha256())
                    },
                    Scopes =
                    {
                        new Scope
                        {
                            Name = "securedfilesscope",
                            DisplayName = "Scope for the securedFiles ApiResource"
                        }
                    },
                    UserClaims = { "role", "admin", "user", "securedFiles", "securedFiles.admin", "securedFiles.user" }
                }
            };
        }
    
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>    {
                        new IdentityResources.OpenId(),
                        new IdentityResources.Profile(),
                        new IdentityResource("dataeventrecordsscope",new []{ "role", "admin", "user", "dataEventRecords", "dataEventRecords.admin" , "dataEventRecords.user" } ),
                        new IdentityResource("securedfilesscope",new []{ "role", "admin", "user", "securedFiles", "securedFiles.admin", "securedFiles.user"} )
            };
        }
    
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client
                {
                    ClientName = "Authclient",
                    ClientId = "client",
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                    ClientSecrets =
                    {
                        new Secret("dataEventRecordsSecret".Sha256())
                    },
    
                    AllowedScopes = new List<string>
                    {
                        "openid",
                        "email",
                        "profile",
                        "dataEventRecords",
                        "aReallyCoolScope",
                        "role"
                    }
                },
            };
        }
    
        public static List<TestUser> GetUsers()
        {
            return new List<TestUser>
            {
                new TestUser
                {
                    SubjectId = "1",
                    Username = "test",
                    Password = "test"
                },
                new TestUser
                {
                    SubjectId = "2",
                    Username = "test1",
                    Password = "test1"
                },
                new TestUser{SubjectId = "48421157", Username = "damienbodadmin", Password = "damienbod",
                  Claims = new Claim[]
                  {
                    new Claim("Name", "damienbodadmin"),
                    new Claim("GivenName", "damienbodadmin"),
                    new Claim("Email", "damien_bod@hotmail.com"),
                    new Claim("EmailVerified", "true", ClaimValueTypes.Boolean),
                    new Claim("Role", "admin"),
                    new Claim("Role", "dataEventRecords.admin"),
                    new Claim("Role", "dataEventRecords.user"),
                    new Claim("Role", "dataEventRecords")
                  }
                },
                new TestUser{SubjectId = "48421158", Username = "damienboduser", Password = "damienbod",
                  Claims = new Claim[]
                  {
                    new Claim("Name", "damienboduser"),
                    new Claim("GivenName", "damienboduser"),
                    new Claim("Email", "damien_bod@hotmail.com"),
                    new Claim("EmailVerified", "true", ClaimValueTypes.Boolean),
                    new Claim("Role", "user"),
                    new Claim("Role", "dataEventRecords.user"),
                    new Claim("Role", "dataEventRecords")
                  }
                }
            };
        }
    }
    

    startup.cs

            public void ConfigureServices(IServiceCollection services)
        {
            var mySqlConnectionString = configuration.GetConnectionString("mySqlConnectionString");
    
            services.AddIdentityServer()
            .AddTemporarySigningCredential()
            .AddInMemoryIdentityResources(Reflexion_HLTR_AuthServer.Config.Config.GetIdentityResources())
            .AddInMemoryApiResources(Reflexion_HLTR_AuthServer.Config.Config.GetApiResources())
            .AddInMemoryClients(Reflexion_HLTR_AuthServer.Config.Config.GetClients())
            .AddTestUsers(Reflexion_HLTR_AuthServer.Config.Config.GetUsers());
    
            services.AddAuthorization(options =>
            {
                options.AddPolicy("dataEventRecordsAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "dataEventRecords.admin");
                });
                options.AddPolicy("dataEventRecordsUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "dataEventRecords.user");
                });
    
            });
    
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(LogLevel.Debug);
            app.UseDeveloperExceptionPage();
    
            app.UseIdentityServer();
    
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
    
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
    
        }        
    

    Web API

    Startup.cs

     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
    
            app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
            {
                Authority = "http://localhost:5000",
                RequireHttpsMetadata = false,
                RoleClaimType = ClaimTypes.Role,
                ApiName = "dataEventRecords"                
            });
    
            app.UseMvc();
    
        } 
    

    EmloyeeController.cs

    [Route("api/Employee")]
    [Authorize]
    public class EmployeeController : Controller
    {
        #region Private Fields
        private IEmployeeService _IEmployeeService = null;
        #endregion
    
        #region Constructor
        public EmployeeController(IEmployeeService _IEmployeeService)
        {
            this._IEmployeeService = _IEmployeeService;
        }
        #endregion
    
        // GET: api/Employee
        [HttpGet]
        [Authorize(Policy = "dataEventRecordsUser")]
        public JsonResult Get()
        {
            var emp = _IEmployeeService.GetEmployee().ToList();
            return Json(emp);
        }
    }
    

1 个答案:

答案 0 :(得分:0)

我修改了GetClients()方法中的AllowedScopes部分,如

AllowedScopes = new List<string>
{
     ClaimTypes.Role
}

然后它适合我。