Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble getting ClaimsPrincipal populated when using EasyAuth to authenticate against AAD on Azure App Service in a Asp.Net Core web app

We have a web app built on Asp.Net core. It doesn't contain any authentication middleware configured in it.

We are hosting on Azure App Service and using the Authentication/Authorization option (EasyAuth) to authenticate against Azure AD.

The authentication works well - we get the requisite headers inserted and we can see the authenticated identity at /.auth/me. But the HttpContext.User property doesn't get populated.

Is this a compatibility issue for Asp.Net core? Or am I doing something wrong?

like image 318
Vaibhav Avatar asked Jan 06 '17 08:01

Vaibhav


1 Answers

I've created a custom middleware that populates the User property until this gets solved by the Azure Team.

It reads the headers from the App Service Authentication and create a a user that will be recognized by the [Authorize] and has a claim on name.

// Azure app service will send the x-ms-client-principal-id when authenticated
app.Use(async (context, next) =>
{

    // Create a user on current thread from provided header
    if (context.Request.Headers.ContainsKey("X-MS-CLIENT-PRINCIPAL-ID"))
    {
        // Read headers from Azure
        var azureAppServicePrincipalIdHeader = context.Request.Headers["X-MS-CLIENT-PRINCIPAL-ID"][0];
        var azureAppServicePrincipalNameHeader = context.Request.Headers["X-MS-CLIENT-PRINCIPAL-NAME"][0];

        // Create claims id
        var claims = new Claim[] {
        new System.Security.Claims.Claim("http://schemas.microsoft.com/identity/claims/objectidentifier", azureAppServicePrincipalIdHeader),
        new System.Security.Claims.Claim("name", azureAppServicePrincipalNameHeader)
        };

        // Set user in current context as claims principal
        var identity = new GenericIdentity(azureAppServicePrincipalIdHeader);
        identity.AddClaims(claims);

        // Set current thread user to identity
        context.User = new GenericPrincipal(identity, null);
    };

    await next.Invoke();
});
like image 68
Jonas Stensved Avatar answered Sep 20 '22 14:09

Jonas Stensved