簡體   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