Skip to content

[Documentation] Add / Remove claims in a filter #890

@juchom

Description

@juchom

Documentation related to component

Customization of claims at application level

Please check all that apply

  • typo
  • documentation doesn't exist
  • documentation needs clarification
  • error(s) in the example
  • needs an example

Description of the issue

I have setup a simple ASP.Net Razor Pages app with AAD B2B authentication and everything works fine.

My problem is the following :

When a user logs in to my application, I need to create a profile for him and store his profile id in a claim and persist this claim for future calls.

In order to make sure the user can't go anywhere in the site until its profile has been set-up, I have created a global filter that check for a claim called userprofile_id which is an Id generated from my database.

I have the following filter :

public class ForceProfileCreationAttribute : IAsyncPageFilter
{
    private readonly MyDbContext _dbContext;
    private readonly ILogger<ForceProfileCreationAttribute> _logger;

    public ForceProfileCreationAttribute(MyDbContext dbContext, ILogger<ForceProfileCreationAttribute> logger)
    {
        _dbContext = dbContext;
        _logger = logger;
    }

    public Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
    {
        return next.Invoke();
    }

    public async Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context)
    {
        // various checks are made here and if the profile exists we add our userprofile_id claim
        var identity = (ClaimsIdentity)context.HttpContext.User.Identity;
        var value = profileDbId.Value.ToString(CultureInfo.InvariantCulture);
        identity.AddClaim(new Claim("userprofile_id", value));
        await context.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, context.HttpContext.User, new AuthenticationProperties())
                                 .ConfigureAwait(false);
        return;
    }
}

If I display the claims on my Razor Pages I can see all of them with the author_id, but on the next request at the begin of the filter the claim is not here anymore.

It's not very clear how to add or remove claims when we leave the OpenIdConnectOptions like in the doc https://github.com/AzureAD/microsoft-identity-web/wiki/customization .

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions