Tuesday, December 4, 2018

Get current user’s principal in Azure function both in v1 and v2 runtimes

Sometimes we need to get current user’s principal in Azure function in order to perform does user has permissions to perform requested action (of course when call to Azure function is done with user context). Recently MS announced feature called ClaimsPrincipal binding data for Azure Functions. With this feature it should be possible to inject client principal as function parameter:

public static IActionResult Run(HttpRequest req, ClaimsPrincipal principal, ILogger log)
{
     // ...
     return new OkResult();
}

Note that according to documentation this feature will be only available for Azure functions which use v2 runtime (which also means that they use .Net Core instead of .Net Framework). I tested it and at least currently this feature is not available for my dev tenant.

Fortunately there is a way to read current user’s principal which works both for v1 and v2. It is based on using special HTTP header X-MS-CLIENT-PRINCIPAL-NAME which contains user name (see Access user claims):

image

So we can read current user’s principal name in Azure function like this:

var headerValues = req.Headers.GetValues("X-MS-CLIENT-PRINCIPAL-NAME");
return headerValues.FirstOrDefault();

and after that perform necessary authorization checks.

Update 2018-12-28: above method with using HTTP headers works but it is possible to replace X-MS-CLIENT-PRINCIPAL-NAME header with other user id and perform calls from behalf of this user. Here is how you may get current user principal using object model:

public static string GetUsernameFromClaim()
{
	if (ClaimsPrincipal.Current == null || ClaimsPrincipal.Current.Identity == null ||
		string.IsNullOrEmpty(ClaimsPrincipal.Current.Identity.Name))
	{
		return string.Empty;
	}

	return ClaimsPrincipal.Current.Identity.Name;
}

s

1 comment:



  1. Full control over your funds while perform transactions with http://bitcoinsxchanger.com trusted fast website working as highest degree of security privacy and professionalism

    ReplyDelete