小编Joh*_*ild的帖子

使用 Active Directory 和 Windows 身份验证在 Blazor 服务器中提供自定义角色

我正在尝试在我的 Blazor 服务器应用程序中提供自定义角色。使用 Windows 身份验证进行身份验证的用户应根据其 Active Directory 组获得这些自定义角色之一,一组代表一个角色。

如果用户在正确的组中,则用户将获得 RoleClaimType 类型的声明。这些声明稍后用于授权某些页面和操作。

我还没有看到任何人对使用 Blazor Server 的 Windows 身份验证和 Active Directory 进行过多讨论,因此我遇到了这些问题。这是我的尝试,但它混合了这里和那里的部分。所以我不确定这是最好的方法还是不安全。

这是我到目前为止想出的..

ClaimTransformer.cs,我从 appsettings.json 获得了广告组。

public class ClaimsTransformer : IClaimsTransformation
{
    private readonly IConfiguration _configuration;

    public ClaimsTransformer(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        var claimsIdentity = (ClaimsIdentity)principal.Identity
        string adGroup = _configuration.GetSection("Roles")
                    .GetSection("CustomRole")
                    .GetSection("AdGroup").Value;
        
        if (principal.IsInRole(adGroup))
        {
            Claim customRoleClaim = new Claim(claimsIdentity.RoleClaimType, "CustomRole");
            claimsIdentity.AddClaim(customRoleClaim);
        }

        return Task.FromResult(principal);
    }
}
Run Code Online (Sandbox Code Playgroud)

要让 Claimstransformer 使用 Authorize 属性,请在 Startup.cs 中使用它:

public …
Run Code Online (Sandbox Code Playgroud)

c# authorization windows-authentication asp.net-core blazor

5
推荐指数
2
解决办法
4730
查看次数