首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于.Net核心web的身份服务器4中基于角色的授权

基于.Net核心web的身份服务器4中基于角色的授权
EN

Stack Overflow用户
提问于 2017-05-27 20:35:28
回答 1查看 2K关注 0票数 0

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

我的应用程序布局类似于

  1. 客户(邮差)
  2. 标识Server4 (auth server)
  3. .Net核心Web应用程序

身份服务器代码

配置文件

代码语言:javascript
复制
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

代码语言:javascript
复制
        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!");
        });

    }        

Startup.cs

代码语言:javascript
复制
 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

代码语言:javascript
复制
[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);
    }
}
EN

回答 1

Stack Overflow用户

发布于 2017-09-22 16:50:32

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

代码语言:javascript
复制
AllowedScopes = new List<string>
{
     ClaimTypes.Role
}

那对我来说很管用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44221391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档