Skip to content

Commit 644b73a

Browse files
author
robertob
committed
cleaning up and consolidating how claim sets are acquired in both easyauth headers and .auth/me json payload cases
1 parent 2dcbc47 commit 644b73a

1 file changed

Lines changed: 17 additions & 29 deletions

File tree

src/KK.AspNetCore.EasyAuthAuthentication/EasyAuthAuthenticationHandler.cs

Lines changed: 17 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
4646
&& !string.IsNullOrEmpty(this.Context.Request.Headers["X-MS-TOKEN-AAD-ID-TOKEN"].ToString()))
4747
{
4848
// build up identity from X-MS-TOKEN-AAD-ID-TOKEN header set by EasyAuth filters if user openid connect session cookie or oauth bearer token authenticated ...
49-
var ticket = this.BuildIdentityFromEasyAuthHeaders(this.Context.Request.Headers);
49+
var ticket = this.BuildIdentityFromEasyAuthRequestHeaders(this.Context.Request.Headers);
5050

5151
this.Logger.LogInformation("Set identity to user context object.");
5252
this.Context.User = ticket.Principal;
@@ -88,68 +88,56 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
8888
}
8989
}
9090

91-
private AuthenticationTicket BuildIdentityFromEasyAuthHeaders(Microsoft.AspNetCore.Http.IHeaderDictionary requestHeaders)
91+
private AuthenticationTicket BuildIdentityFromEasyAuthRequestHeaders(Microsoft.AspNetCore.Http.IHeaderDictionary requestHeaders)
9292
{
9393
var name = requestHeaders["X-MS-CLIENT-PRINCIPAL-NAME"][0];
94-
var idToken = requestHeaders["X-MS-TOKEN-AAD-ID-TOKEN"][0];
95-
var providerName = requestHeaders["X-MS-CLIENT-PRINCIPAL-IDP"][0];
96-
9794
this.Logger.LogDebug("payload was fetched from easyauth headers, name: {0}", name);
9895

9996
var identity = new GenericIdentity(name, "AuthenticationTypes.Federation"); // setting ClaimsIdentity.AuthenticationType to value that azuread non-easyauth setups use
10097

10198
this.Logger.LogInformation("building claims from payload...");
10299

103-
// jwt token decode c# -> https://stackoverflow.com/questions/38340078/how-to-decode-jwt-token/38911599#38911599
104-
// nuget.org search on "System.IdentityModel.Tokens.Jwt MicrosoftIdentityModel.Tokens" ->
105-
// using System.IdentityModel.Tokens.Jwt 27.8m vs MicrosoftIdentityModel.Tokens 17.5m downloads both v5.3.0 released 10/05/2018
106-
var idTokenJwt = new JwtSecurityToken(idToken);
100+
var xMsClientPrincipal = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(requestHeaders["X-MS-CLIENT-PRINCIPAL"][0])));
101+
//var nameidentifier = xMsClientPrincipal["claims"].Children<JObject>().FirstOrDefault(c => c["typ"].ToString() == ClaimTypes.NameIdentifier)?["val"].ToString();
107102
var claims = new List<Claim>();
108-
foreach (var claim in idTokenJwt.Claims as List<Claim>)
103+
foreach (var claim in xMsClientPrincipal["claims"].Children<JObject>())
109104
{
110-
if (claim.Type == "amr")
105+
if (claim["typ"].ToString() == "http://schemas.microsoft.com/claims/authnmethodsreferences")
111106
{
112-
foreach (var item in claim.Value.Split(','))
107+
foreach (var item in claim["val"].ToString().Split(','))
113108
{
114109
claims.Add(new Claim(ClaimTypes.Authentication, item));
115110
}
116111
}
117-
else if (claim.Type == "roles")
112+
else if (claim["typ"].ToString() == "roles")
118113
{
119-
foreach (var item in claim.Value.Split(','))
114+
foreach (var item in claim["val"].ToString().Split(','))
120115
{
121116
//(User.Identity as ClaimsIdentity).RoleClaimType must match type that role claims are assigned to for Authorization and IsInRole to work
122117
claims.Add(new Claim(ClaimTypes.Role, item));
123118
}
124119
}
125-
else // if (claim.Type != "c_hash")
120+
else
126121
{
127122
//(User.Identity as ClaimsIdentity).NameClaimType must be what name claim is assigned to for User.Identity.Name to work
128-
claims.Add(new Claim(claim.Type, claim.Value));
123+
claims.Add(new Claim(claim["typ"].ToString(), claim["val"].ToString()));
129124
}
130125
}
131126

132127
this.Logger.LogInformation("Add claims to new identity");
133128

134129
identity.AddClaims(claims);
135-
var xMsClientPrincipal = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(requestHeaders["X-MS-CLIENT-PRINCIPAL"][0])));
136-
var nameidentifier = xMsClientPrincipal["claims"].Children<JObject>().FirstOrDefault(c => c["typ"].ToString() == ClaimTypes.NameIdentifier)?["val"].ToString();
137-
//foreach (var claim in xMsClientPrincipal["claims"]) { if (claim["typ"].ToString() == ClaimTypes.NameIdentifier) { nameidentifier = claim["val"].ToString(); } } // line above works not required
138-
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, nameidentifier));
139130
//identity.AddClaim(new Claim("id_token", idToken)); // don't think we should be including this
140131
//identity.AddClaim(new Claim("http://schemas.microsoft.com/claims/authnclassreference", 1)); // don't think we need to add this
141-
if (!(identity.Claims as List<Claim>).Exists(claim => claim.Type == "scp")) identity.AddClaim(new Claim("scp", "user_impersonation")); // not sure why easyauth not including this
142-
identity.AddClaim(new Claim("provider_name", providerName));
132+
if (!(identity.Claims as List<Claim>).Exists(claim => claim.Type == "scp")) identity.AddClaim(new Claim("scp", "user_impersonation")); // not sure why easyauth is dropping this
133+
identity.AddClaim(new Claim("provider_name", requestHeaders["X-MS-CLIENT-PRINCIPAL-IDP"][0]));
143134
var genericPrincipal = new GenericPrincipal(identity, null);
144135
return new AuthenticationTicket(genericPrincipal, EasyAuthAuthenticationDefaults.AuthenticationScheme);
145136
}
146137

147138
private AuthenticationTicket BuildIdentityFromEasyAuthMeJson(JObject payload)
148139
{
149140
var name = payload["user_id"].Value<string>(); // X-MS-CLIENT-PRINCIPAL-NAME
150-
var idToken = payload["id_token"].Value<string>(); // X-MS-TOKEN-AAD-ID-TOKEN
151-
var providerName = payload["provider_name"].Value<string>(); // X-MS-CLIENT-PRINCIPAL-IDP
152-
153141
this.Logger.LogDebug("payload was fetched from easyauth me json, name: {0}", name);
154142

155143
var identity = new GenericIdentity(name, "AuthenticationTypes.Federation"); // setting ClaimsIdentity.AuthenticationType to value that azuread non-easyauth setups use
@@ -159,7 +147,7 @@ private AuthenticationTicket BuildIdentityFromEasyAuthMeJson(JObject payload)
159147
var claims = new List<Claim>();
160148
foreach (var claim in payload["user_claims"])
161149
{
162-
if (claim["typ"].ToString() == "amr")
150+
if (claim["typ"].ToString() == "http://schemas.microsoft.com/claims/authnmethodsreferences")
163151
{
164152
foreach (var item in claim["val"].ToString().Split(','))
165153
{
@@ -174,7 +162,7 @@ private AuthenticationTicket BuildIdentityFromEasyAuthMeJson(JObject payload)
174162
claims.Add(new Claim(ClaimTypes.Role, item));
175163
}
176164
}
177-
else // if (claim["typ"].ToString() != "c_hash")
165+
else
178166
{
179167
//(User.Identity as ClaimsIdentity).NameClaimType must be what name claim is assigned to for User.Identity.Name to work
180168
claims.Add(new Claim(claim["typ"].ToString(), claim["val"].ToString()));
@@ -186,8 +174,8 @@ private AuthenticationTicket BuildIdentityFromEasyAuthMeJson(JObject payload)
186174
identity.AddClaims(claims);
187175
//identity.AddClaim(new Claim("id_token", idToken)); // don't think we should be including this
188176
//identity.AddClaim(new Claim("http://schemas.microsoft.com/claims/authnclassreference", 1)); // don't think we need to add this
189-
if (!(identity.Claims as List<Claim>).Exists(claim => claim.Type == "scp")) identity.AddClaim(new Claim("scp", "user_impersonation")); // not sure why easyauth not including this
190-
identity.AddClaim(new Claim("provider_name", providerName));
177+
if (!(identity.Claims as List<Claim>).Exists(claim => claim.Type == "scp")) identity.AddClaim(new Claim("scp", "user_impersonation")); // not sure why easyauth is dropping this
178+
identity.AddClaim(new Claim("provider_name", payload["provider_name"].Value<string>())); // X-MS-CLIENT-PRINCIPAL-IDP
191179
var genericPrincipal = new GenericPrincipal(identity, null);
192180
return new AuthenticationTicket(genericPrincipal, EasyAuthAuthenticationDefaults.AuthenticationScheme);
193181
}

0 commit comments

Comments
 (0)