c# - Blazor WASM + AAD B2C + 自定义授权

标签 c# authorization azure-ad-b2c blazor-client-side claims

我有一个 Blazor 客户端 (WASM) 应用程序,它与 AAD B2C 集成以进行身份​​验证。

鉴权后,我想调用自己的API获取进一步的鉴权信息。我想这样做而不是让 B2C 调用我的 API 的原因是我将有一系列不同的应用程序使用相同的 B2C,具有不同的声明、角色和其他信息等。

我已经尝试了我能找到的所有教程,但似乎没有任何连接。

我的 Program.cs 有这个:

builder.Services.AddMsalAuthentication(options =>
{
    var settings = config.AzureAdB2C;

    var authentication = options.ProviderOptions.Authentication;
    authentication.Authority = $"{settings.Instance}{settings.Domain}/{settings.SignInPolicy}";
    authentication.ClientId = settings.ClientApplicationId;
    authentication.ValidateAuthority = false;
    options.ProviderOptions.DefaultAccessTokenScopes.Add($"{settings.ServerAppId}/{settings.DefaultScope}");
    //options.ProviderOptions.Cache.CacheLocation = "localStorage";
});

builder.Services.AddOptions();
builder.Services.AddAuthorizationCore();

例如,我试过这个:

builder.Services.AddScoped<IClaimsTransformation, UserInfoClaims>();

public class UserInfoClaims : IClaimsTransformation
{
    private static IEnumerable<SimpleClaim> roles;
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        ...

但它没有被击中。

是否可以在 B2C 身份验证后重写 WASM 中的声明?

如果没有,是否可以在成功验证后连接到一个事件来管理我自己的类似角色的替代方案?

最佳答案

这可以通过实现您自己的 AccountClaimsPrincipalFactory 来完成

    public class ExampleClaimsPrincipalFactory<TAccount> : AccountClaimsPrincipalFactory<TAccount> 
    where TAccount : RemoteUserAccount
{
    public ExampleClaimsPrincipalFactory(IAccessTokenProviderAccessor accessor)
    : base(accessor)
    { 
      //Any dependency injection or construction of objects 
      //inside this constructor usually leads to wasm memory exceptions
    }

    public async override ValueTask<ClaimsPrincipal> CreateUserAsync(TAccount account, RemoteAuthenticationUserOptions options)
    {
        var user = await base.CreateUserAsync(account, options);

        if (account != null)
        {     
            //Add logic here to get custom user information
            //Add Claims to the user identity like so
            var identity = user.Identity as ClaimsIdentity;
            identity.AddClaim(new Claim("type", "value"));
        }

        return user;
    }
}

然后在启动时添加身份验证时执行以下操作

builder.Services.AddMsalAuthentication()
    .AddAccountClaimsPrincipalFactory<ExampleClaimsPrincipalFactory<RemoteUserAccount>>();

关于c# - Blazor WASM + AAD B2C + 自定义授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66135694/

相关文章:

C# System.Drawing.Printing.PrintDocument 转 PDF 推荐?

c# - 控制台或图形游戏设计?

javascript - 在跨站点域中自动登录

asp.net-mvc-4 - ASP.NET MVC DotNetOpenAuth 授权服务器操作方法

c# - 在 OnAuthorization 之前执行的 ASP.NET MVC 全局或 BaseController ActionFilter

c# - 在 Silverlight 中使用 C# 而不是 XAML

angular - Azure B2C AD 重定向到 Angular 应用程序

asp.net - Azure AD B2C - 多个子域

azure-ad-b2c - Azure AD B2C 将声明添加到自定义策略中的 id_token

javascript - 如何在超链接点击时调用 javascript 警报,其中包含单引号消息?