I have an Azure Function 2.x (Asp.net Core) and am authenticating with Azure AD. I'm trying to access the logged-in user's Claims after authentication. Previously using Azure Functions 1.x we would get the Claims using ClaimsPrincipal.Current, as seen in the code below:
using System.Net;
using System.Collections.Generic;
using System.Security.Claims;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
public static HttpResponseMessage Run(HttpRequestMessage req, out object document, TraceWriter log)
{
string name = ClaimsPrincipal.Current.FindFirst("name").Value;
log.Info($"name is {name}");
return req.CreateResponse(HttpStatusCode.OK, "Done");
}
Any guidance on how we access Claims in Azure Functions 2.x using .Net Core?
For Java apps, the claims are accessible from the Tomcat servlet. For Azure Functions, ClaimsPrincipal.Current is not populated for .NET code, but you can still find the user claims in the request headers, or get the ClaimsPrincipal object from the request context or even through a binding parameter.
Azure Functions version 3.x is highly backwards compatible to version 2.x. Many apps can safely upgrade to 3.x without any code changes. While moving to 3.x is encouraged, run extensive tests before changing the major version in production apps. The following are the language-specific changes to be aware of before upgrading a 2.x app to 3.x.
An Azure Static Web Apps-specific unique identifier for the user. The value is unique on a per-app basis. For instance, the same user returns a different userId value on a different Static Web Apps resource. The value persists for the lifetime of a user. If you delete and add the same user back to the app, a new userId is generated.
Well because the Azure function has to call the extension method itself and you may want access to the ClaimsPrincipal instance in a dependency injected service and not directly in the Azure Function. If you’re not in the Azure Function then you don't have access to the HttpRequestData instance. So how do we solve this?
This feature is now supported in C# in Azure Functions 2.0. You can now add ClaimsPrincipal
as a parameter to your HttpTrigger
function's signature, or you can access it on the HttpRequest
object via req.HttpContext.User
.
Support should be coming soon to JavaScript, and eventually all languages should support this feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With