Azure Apps EasyAuth claims with .NET Core

Solution 1:

According to your description, I found a similar issue. As I known, there is no any framework for you to achieve it currently. Based on my understanding, if you prefer to retrieve all claims when using Azure App Service EasyAuth, I assumed that you'd better make a server-side request to the in-build endpoint /.auth/me to retrieve the claims as follows:

Startup.cs > Configure

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];

        #region extract claims via call /.auth/me
        //invoke /.auth/me
        var cookieContainer = new CookieContainer();
        HttpClientHandler handler = new HttpClientHandler()
        {
            CookieContainer = cookieContainer
        };
        string uriString = $"{context.Request.Scheme}://{context.Request.Host}";
        foreach (var c in context.Request.Cookies)
        {
            cookieContainer.Add(new Uri(uriString), new Cookie(c.Key, c.Value));
        }
        string jsonResult = string.Empty;
        using (HttpClient client = new HttpClient(handler))
        {
            var res = await client.GetAsync($"{uriString}/.auth/me");
            jsonResult = await res.Content.ReadAsStringAsync();
        }

        //parse json
        var obj = JArray.Parse(jsonResult);
        string user_id = obj[0]["user_id"].Value<string>(); //user_id

        // Create claims id
        List<Claim> claims = new List<Claim>();
        foreach (var claim in obj[0]["user_claims"])
        {
            claims.Add(new Claim(claim["typ"].ToString(), claim["val"].ToString()));
        }

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

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

    await next.Invoke();
});

Solution 2:

I created a middleware you can use to get a proper identity in .net core with ez auth. You can see my answer with the links to the nuget and source here:

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