ASP.NET Core 6.0 / Razor pages / add info about currently logged in user to the Session

247 Views Asked by At

I have an ASP.NET Core 6.0 web app using Razor pages. For authentication, I'm using the MS Identity subsystem / OpenID Connect, with Azure Active Directory as my identity provider. This all works quite nicely - users are asked to provide their usual credentials, and in the course of the app, I can always get the HttpContext.User claims principal and inspect whatever I need about the currently logged on user.

What I would like to do is store some information (e.g. the user-principal name claim's value of the logged in user) into the ASP.NET Core session state (because I need to access this in places where I do not have access to the HttpContext.User property).

I was looking at writing some type of a filter to do this - only to discover that neither action filters, nor endpoint filters (in ASP.NET Core 7.0), are supported in Razor pages ;-(

OK - so that leaves me with the challenge of when exactly I can put that information into session. Is there some "hook" I can tap into that is called upon successful authentication of a user? Or is there any other "global" location where I could tap into the HttpContext.User property and extract the value from the userPrincipalName claim?

Do I need to create a separate base class derived from PageModel, that I can then use as the base class for all my specific Razor page models? Or is there an easier way?

1

There are 1 best solutions below

1
Guru Stron On BEST ANSWER

If I understand the question correctly the approach would be to register a custom middleware after the calls to auth and UseSession:

app.UseAuthorization();
app.UseSession();

// ...

app.Use(async (ctx, next) =>
{
    if (ctx.User.Identity?.IsAuthenticated ?? false)
    {
        // ctx.Session.Set(...);
    }
    await next();
});

// ...

app.MapRazorPages();