簡體   English   中英

Blazor WASM + AAD B2C + 自定義授權

[英]Blazor WASM + AAD B2C + Custom Authorisation

我有一個與 AAD B2C 集成以進行身份驗證的 Blazor 客戶端 (WASM) 應用程序。

認證后想調用自己的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>>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM