繁体   English   中英

身份服务器 4 中基于角色的授权与 .Net 核心 Web API

[英]Role based authorization in identity server 4 with .Net core web API

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

我的应用程序布局就像

  1. 客户(邮递员)
  2. 身份服务器 4(身份验证服务器)
  3. .Net 核心 Web API 应用

身份服务器代码

配置文件

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")
              }
            }
        };
    }
}

启动文件

        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!");
        });

    }        

网页接口

启动文件

 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();

    } 

员工控制器.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);
    }
}

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

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

然后它对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM