简体   繁体   English

如何在 ASP.NET Core 中自定义/覆盖 User.IsInRole

[英]How to custom/override User.IsInRole in ASP.NET Core

我是 ASP.NET Core 的新手,我在控制器的 User 属性(在 ClaimsPrincipal 类中)中看到,它有 User.IsInRole 方法,所以我如何覆盖它以调用我的服务依赖项并在我的应用程序中注册(我不想使用扩展方法)。

You can use ClaimsTransformation:您可以使用 ClaimsTransformation:

public class Startup
{
    public void ConfigureServices(ServiceCollection services)
    {
        // ...
        services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
    }
}

public class CustomClaimsPrincipal : ClaimsPrincipal
{
    public CustomClaimsPrincipal(IPrincipal principal): base(principal)
    {}

    public override bool IsInRole(string role)
    {
        // ...
        return base.IsInRole(role);
    }
}

public class ClaimsTransformer : IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        var customPrincipal = new CustomClaimsPrincipal(principal) as ClaimsPrincipal;
        return Task.FromResult(customPrincipal);
    }
}

Controller method:控制器方法:

[Authorize(Roles = "Administrator")]
public IActionResult Get()
{
    // ...
}

Role checking by Authorize attribute will use your overrided IsInRole method通过 Authorize 属性检查角色将使用您覆盖的 IsInRole 方法

For User.IsInRole , it is ClaimsPrincipal which is not registered as service, so, you could not replace ClaimsPrincipal , and you could not override IsInRole .对于User.IsInRole ,它是ClaimsPrincipal未注册为服务,因此,您无法替换ClaimsPrincipal ,也无法覆盖IsInRole

For a workaround, if you would not use extension method, you could try to implement your own ClaimsPrincipal and Controller .对于解决方法,如果您不使用扩展方法,您可以尝试实现自己的ClaimsPrincipalController

  • CustomClaimsPrincipal which is inherited from ClaimsPrincipal CustomClaimsPrincipal继承自ClaimsPrincipal

     public class CustomClaimsPrincipal: ClaimsPrincipal { public CustomClaimsPrincipal(IPrincipal principal):base(principal) { } public override bool IsInRole(string role) { return base.IsInRole(role); } }
  • ControllerBase to change ClaimsPrincipal User to CustomClaimsPrincipal User ControllerBaseClaimsPrincipal User更改为CustomClaimsPrincipal User

     public class ControllerBase: Controller { public new CustomClaimsPrincipal User => new CustomClaimsPrincipal(base.User); }
  • Change the Controller from inheriting ControllerBase .更改Controller继承ControllerBase

     public class HomeController : ControllerBase { public IActionResult About() { ViewData["Message"] = "Your application description page."; var result = User.IsInRole("Admin"); return View(); }
  • Change the logic in public override bool IsInRole(string role) based on your requirement根据您的要求更改public override bool IsInRole(string role)的逻辑

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

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