1

I will be accessing several tables to determine if a user is "Validated" or not as well as adding custom roles to a Windows authenticated user for authorization. For now I'm running a test in a basic .net Core web application just to see how I should be doing this. I have setup a RequiredClaim in my Fallback Policy and a ClaimsLoader and it works great:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();

        services.AddTransient<IClaimsTransformation, ClaimsLoader>();
        services.AddAuthentication(IISDefaults.AuthenticationScheme);

        services.AddAuthorization(options =>
        {
            options.FallbackPolicy = new AuthorizationPolicyBuilder()
                .RequireClaim("ValidatedUser")
                .Build();
        });
    }


    public class ClaimsLoader : IClaimsTransformation
    {
       public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
       {
          var claimsIdentity = (ClaimsIdentity)principal.Identity;
          claimsIdentity.AddClaim(new Claim("ValidatedUser", ""));
          return await Task.FromResult(principal);
       }
    }

As long as that AddClaim line is in there, they can access the app, without it they get a not-authorized response which is what I want.

Based on what I've read I thought any claims/roles I add in the transformation should come back each time but they do not. In the code above I have the AddClaim running every time so it's working, but in reality I will be going to a database to determine if I should add that claim which is an expensive process. I want to persist the results across multiple requests. So I want to check if the claim is already there and not bother getting it again if it is. For whatever reason it is NEVER there when it comes back for a second request.

From what I've read here back in 2.x the claims should persist: https://philipm.at/2018/aspnetcore_claims_with_windowsauthentication.html

But here in my 3.1 application they do not.

Kevin Fizz
  • 197
  • 1
  • 2
  • 8
  • I'm afraid you'll have to accept that TransformAsync is called on every request. The good news is that caching will reduce number of calls to db. Complete solution here: https://stackoverflow.com/a/63441045/14072498 – Roar S. Dec 15 '20 at 23:59
  • 2
    That is the exact code I was already working with. :) I expect TransformAsync to be called on every request I was just confused how my article seemed to think that the roles and claims added at TransformAsync would be persisted: "..which means for IIS Authentication they run only once and whatever claims we add to the collection are cached for as long as the user is logged in." So I had expected to put code in TransformAsync to make sure I don't add them in TWICE but it doesn't matter - anything I add is only there for that single request. Thanks! – Kevin Fizz Dec 16 '20 at 15:10

0 Answers0