Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Function 2.x - Get Current User's Claims

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?

like image 572
desflan Avatar asked Aug 07 '18 15:08

desflan


People also ask

How do I find the user claims in Azure Functions?

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.

Is Azure Functions 3 backwards compatible with Azure 2?

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.

What is userid in azure static web apps?

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.

Why can't I access the claimsprincipal instance in an azure function?

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?


Video Answer


1 Answers

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.

like image 137
Connor McMahon Avatar answered Sep 18 '22 21:09

Connor McMahon