Reputation: 33
I want to write some ASP .NET Core middleware to turn the Azure Apps EasyAuth HTTP headers into claims. I've found two ways to do it:
Parse the token that EasyAuth provides in the HTTP header. This doesn't seem like a generic solution as I'd have to write code to parse tokens for every identity provider.
Make a server-side request to /.auth/me. This returns some JSON which I'd like to convert to claims but I'm not sure if I have to do this manually or there is framework support for it.
Is #2 the best approach, and is there any framework support for it?
Upvotes: 1
Views: 4782
Reputation: 111
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:
Upvotes: 3
Reputation: 18465
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();
});
Upvotes: 7