This post was most recently updated on August 31st, 2022.
3 min read.This post describes how to get the currently logged-in user using ASP.NET Core. This is compared with how it’s done in ASP.NET Framework.
Background
In ASP.NET Core (and .NET Core in general), a lot of things are done a bit differently than what you might be used to if you’re coming from the .NET Framework world. That’s what I’ve been learning building more and more stuff with it, instead of good old .NET Framework. The learning curve is definitely there, but it’s not that bad – most of the things work in a similar fashion, but a huge number of details are different.
In ASP.NET Framework, you’d do this by accessing HttpContext.Current.User and its properties (see below for an example), in .NET Core this is handled via dependency injection.
var username = HttpContext.Current.User.Identity.Name;
You can’t do this in (most versions of) .NET Core. How to do it there, then?
Solution
Let’s go through the steps first on a high level, and then take a closer look below.
Time needed: 10 minutes
How to get the current user in ASP.NET Core?
- Make sure your application has permissions to request user properties or claims
We obviously need to make sure our app actually gets enough information from AAD. That means your Azure AD app registration needs to be properly configured.
Explaining this takes a while – it’s described in a separate blog post. See details here. - Modify your app startup to add the required background services
ConfigureServices() needs a quick tweak to enable us to access HttpContext.
See a code sample here. - Implement the property/claim enumeration in your code
Okay – so now we’ll access the user context and find a claim we like!
The code is lengthy, so it’s described a little bit further down in the article. See a sample and details here.
Now, that’s good – let’s take a closer look at these 3 steps below!
Background
Now I’ll describe how to manage user identity when developing your application – before that, you need to configure your application registration so that your identity provider supplies you with the user information in the first place. For Azure AD, see my other post, here:
https://www.koskila.net/iterating-group-memberships-using-claims-in-net-core/
When that all is done, let’s jump into how you can access User/Identity in your program!
Modify your Startup
First, you add this to your Startup.cs -file’s using statements:
using Microsoft.AspNetCore.Http
And then, in ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
// omitted for clarity
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
Or if you’re at least on .NET Core 3.0, you can do this as well:
public void ConfigureServices(IServiceCollection services)
{
// omitted for clarity
services.Add<HttpContextAccessor>();
}
Accessing the User Properties in your code
Then you add these pieces of code to your Controller, database context, or other class:
- Private variable to hold the injected reference to our HttpContextAccessor
- New variable with the correct type (or interface) to the class constructor (like IHttpContextAccessor httpContextAccessor below)
- Assignment from the injected variable (in the constructor) to the hidden private variable (to make the reference available outside the constructor)
Below, my code is shown accessing the HttpContext (and through that, Current User) in a DbContext class. It’s assigned in the constructor, after which you may use it in any other method!
private readonly IHttpContextAccessor _httpContextAccessor;
public ApplicationDbContext(DbContextOptions options, IHttpContextAccessor httpContextAccessor) : base(options)
{
_httpContextAccessor = httpContextAccessor;
}
For our little example call further below, you’ll need to add a reference to Claims like this:
using System.Security.Claims;
And finally, you call it like this – for example, to get the reference to the user, and grab their id:
var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
This can be injected to Controllers and Views, Custom Components and if need be, properties passed to background Threads (don’t pass the context! That’ll break.)
How does this work with Blazor pages?
Ahh, Blazor – the cool kid on the block! Blazor pages require the same set-up (Startup.cs stuff), but you can just inject the service like this:
@page "/"
@using System.Security.Claims
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor
<h1>Hello, world!</h1>
Welcome to your new app, @user.
<SurveyPrompt Title="How is Blazor working for you?" />
@code {
private string user = "";
protected override void OnInitialized()
{
user = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
base.OnInitialized();
}
}
Nice and easy!
What about pure & classic Razor pages?
Okay, so here it’s different because Razor takes care of some of the background work for you. If you’re using Razor pages, you can just do this:
@{
var username = HttpContext.User.Identity.Name;
}
That’s because Razor exposes HttpContext in Razor.Component.
And with this, you should be good! :)
Did it help? Or is it lacking in detail? Any other comments? Let me know in the comments section below!
- “Performing cleanup” – Excel is stuck with an old, conflicted file and will never recover. - November 12, 2024
- How to add multiple app URIs for your Entra app registration? - November 5, 2024
- How to access Environment Secrets with GitHub Actions? - October 29, 2024