Window Authentication .Net Core Application Kentico 13

Izhar Anjum asked on February 1, 2024 13:45

CMS.Membership and MembershipContext returning public anonymous user while using window authentication in .Net Core application

Recent Answers


Juraj Ondrus answered on February 2, 2024 07:38

What version and hotfix are you using? There were several bugs fixed in the past. If not using the latest one, please apply it. Also, how did you implemented the AD authentication in your app? Is the user created in the Kentico DB?

0 votesVote for this answer Mark as a Correct answer

Ben Quinlan answered on February 13, 2024 14:18

I have had experience with a Kentico 13 solution using identity providers where the MembershipContext.AuthenticatedUser would return the public anonymous user even though we could clearly see the ClaimsIdentity stored in the HttpContext.User principal.

In our particular case we were eventually able to identify that this was due to the order of the order in which the application middleware was configured and how Kentico stored MembershipContext and RequestContext state once it was initially defined.

When we defined the following in the startup.cs we found that it would result in the above case.

app.UseKentico();
app.UseAuthentication();
app.UseAuthorization();

If we instead moved the UseKentico below the other middleware, we found our MembershipContext then worked correctly for users authenticated against the presentation website. Unfortunately this success was short lived as changing this order broke how authentication was handled for content editors through the admin site. Essentially we could have one type of authentication or the other, but not both.

In our case we tracked the specific issue down to how the RequestContext and MembershipContexts are initialised during the call to the UseKentico middleware. As the identity was not set at the point, given the middleware for authentication had not yet been called, the principal object was found to be empty. This was then cached by the request context and never updated. The 'fix' we implemented for this was simply to include some middleware that identified a mismatch between having an authenticated claims user and whether the RequestContext was flagged as authenticated. If there was a mismatch, we then cleared the RequestContext and MembershipContext to allow them to reinitialise correctly.

app.Use(next => ctx =>
{
    if (!RequestContext.IsUserAuthenticated && ctx.User.Identity.IsAuthenticated)
    {
        RequestContext.Clear();
        MembershipContext.Clear();
    }
    return next(ctx);
});
0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.