1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
|
//-----------------------------------------------------------------------
// <copyright file="AzureADClient.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace DotNetOpenAuth.AspNet.Clients {
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Tokens;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml;
using DotNetOpenAuth.Messaging;
using Validation;
/// <summary>
/// The AzureAD client.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "AzureAD", Justification = "Brand name")]
public sealed class AzureADClient : OAuth2Client {
#region Constants and Fields
/// <summary>
/// The authorization endpoint.
/// </summary>
private const string AuthorizationEndpoint = "https://login.windows.net/common/oauth2/authorize";
/// <summary>
/// The token endpoint.
/// </summary>
private const string TokenEndpoint = "https://login.windows.net/common/oauth2/token";
/// <summary>
/// The name of the graph resource.
/// </summary>
private const string GraphResource = "https://graph.windows.net";
/// <summary>
/// The URL to get the token decoding certificate from.
/// </summary>
private const string MetaDataEndpoint = "https://login.windows.net/evosts.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml";
/// <summary>
/// The URL for AzureAD graph.
/// </summary>
private const string GraphEndpoint = "https://graph.windows.net/";
/// <summary>
/// The id of the STS.
/// </summary>
private const string STSName = "https://sts.windows.net";
/// <summary>
/// The app id.
/// </summary>
private readonly string appId;
/// <summary>
/// The app secret.
/// </summary>
private readonly string appSecret;
/// <summary>
/// The resource to target.
/// </summary>
private readonly string resource;
/// <summary>
/// Encoding cert.
/// </summary>
private static X509Certificate2[] encodingcert;
/// <summary>
/// Hash algo used by the X509Cert.
/// </summary>
private static HashAlgorithm hash;
/// <summary>
/// The tenantid claim for the authcode.
/// </summary>
private string tenantid;
/// <summary>
/// The userid claim for the authcode.
/// </summary>
private string userid;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="AzureADClient"/> class.
/// </summary>
/// <param name="appId">
/// The app id.
/// </param>
/// <param name="appSecret">
/// The app secret.
/// </param>
public AzureADClient(string appId, string appSecret)
: this(appId, appSecret, GraphResource) {
}
/// <summary>
/// Initializes a new instance of the <see cref="AzureADClient"/> class.
/// </summary>
/// <param name="appId">
/// The app id.
/// </param>
/// <param name="appSecret">
/// The app secret.
/// </param>
/// <param name="resource">
/// The resource of oauth request.
/// </param>
public AzureADClient(string appId, string appSecret, string resource)
: base("azuread") {
Requires.NotNullOrEmpty(appId, "appId");
Requires.NotNullOrEmpty(appSecret, "appSecret");
Requires.NotNullOrEmpty(resource, "resource");
this.appId = appId;
this.appSecret = appSecret;
this.resource = resource;
}
#endregion
#region Methods
/// <summary>
/// The get service login url.
/// </summary>
/// <param name="returnUrl">
/// The return url.
/// </param>
/// <returns>An absolute URI.</returns>
protected override Uri GetServiceLoginUrl(Uri returnUrl) {
var builder = new UriBuilder(AuthorizationEndpoint);
builder.AppendQueryArgs(
new Dictionary<string, string> {
{ "client_id", this.appId },
{ "redirect_uri", returnUrl.AbsoluteUri },
{ "response_type", "code" },
{ "resource", this.resource },
});
return builder.Uri;
}
/// <summary>
/// The get user data.
/// </summary>
/// <param name="accessToken">
/// The access token.
/// </param>
/// <returns>A dictionary of profile data.</returns>
protected override NameValueCollection GetUserData(string accessToken) {
var userData = new NameValueCollection();
try {
AzureADGraph graphData;
WebRequest request =
WebRequest.Create(
GraphEndpoint + this.tenantid + "/users/" + this.userid + "?api-version=2013-04-05");
request.Headers = new WebHeaderCollection();
request.Headers.Add("authorization", accessToken);
using (var response = request.GetResponse()) {
using (var responseStream = response.GetResponseStream()) {
graphData = JsonHelper.Deserialize<AzureADGraph>(responseStream);
}
}
// this dictionary must contains
userData.AddItemIfNotEmpty("id", graphData.ObjectId);
userData.AddItemIfNotEmpty("username", graphData.UserPrincipalName);
userData.AddItemIfNotEmpty("name", graphData.DisplayName);
return userData;
} catch (Exception e) {
System.Diagnostics.Debug.WriteLine(e.ToStringDescriptive());
return userData;
}
}
/// <summary>
/// Obtains an access token given an authorization code and callback URL.
/// </summary>
/// <param name="returnUrl">
/// The return url.
/// </param>
/// <param name="authorizationCode">
/// The authorization code.
/// </param>
/// <returns>
/// The access token.
/// </returns>
protected override string QueryAccessToken(Uri returnUrl, string authorizationCode) {
try {
var entity =
MessagingUtilities.CreateQueryString(
new Dictionary<string, string> {
{ "client_id", this.appId },
{ "redirect_uri", returnUrl.AbsoluteUri },
{ "client_secret", this.appSecret },
{ "code", authorizationCode },
{ "grant_type", "authorization_code" },
{ "api_version", "1.0" },
});
WebRequest tokenRequest = WebRequest.Create(TokenEndpoint);
tokenRequest.ContentType = "application/x-www-form-urlencoded";
tokenRequest.ContentLength = entity.Length;
tokenRequest.Method = "POST";
using (Stream requestStream = tokenRequest.GetRequestStream()) {
var writer = new StreamWriter(requestStream);
writer.Write(entity);
writer.Flush();
}
HttpWebResponse tokenResponse = (HttpWebResponse)tokenRequest.GetResponse();
if (tokenResponse.StatusCode == HttpStatusCode.OK) {
using (Stream responseStream = tokenResponse.GetResponseStream()) {
var tokenData = JsonHelper.Deserialize<OAuth2AccessTokenData>(responseStream);
if (tokenData != null) {
AzureADClaims claimsAD;
claimsAD = this.ParseAccessToken(tokenData.AccessToken, true);
if (claimsAD != null) {
this.tenantid = claimsAD.Tid;
this.userid = claimsAD.Oid;
return tokenData.AccessToken;
}
return string.Empty;
}
}
}
return null;
} catch (Exception e) {
System.Diagnostics.Debug.WriteLine(e.ToStringDescriptive());
return null;
}
}
/// <summary>
/// Base64 decode function except that it switches -_ to +/ before base64 decode
/// </summary>
/// <param name="str">
/// The string to be base64urldecoded.
/// </param>
/// <returns>
/// Decoded string as string using UTF8 encoding.
/// </returns>
private static string Base64URLdecode(string str) {
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
return encoder.GetString(Base64URLdecodebyte(str));
}
/// <summary>
/// Base64 decode function except that it switches -_ to +/ before base64 decode
/// </summary>
/// <param name="str">
/// The string to be base64urldecoded.
/// </param>
/// <returns>
/// Decoded string as bytes.
/// </returns>
private static byte[] Base64URLdecodebyte(string str) {
// First replace chars and then pad per spec
str = str.Replace('-', '+').Replace('_', '/');
str = str.PadRight(str.Length + ((4 - (str.Length % 4)) % 4), '=');
return Convert.FromBase64String(str);
}
/// <summary>
/// Validate whether the unsigned value is same as signed value
/// </summary>
/// <param name="uval">
/// The raw input of the string signed using the key
/// </param>
/// <param name="sval">
/// The signature of the string
/// </param>
/// <param name="certthumb">
/// The thumbprint of cert used to encrypt token
/// </param>
/// <returns>
/// True if same, false otherwise.
/// </returns>
private static bool ValidateSig(byte[] uval, byte[] sval, byte[] certthumb) {
try {
bool ret = false;
X509Certificate2[] certx509 = GetEncodingCert();
string certthumbhex = string.Empty;
// Get the hexadecimail representation of the certthumbprint
for (int i = 0; i < certthumb.Length; i++) {
certthumbhex += certthumb[i].ToString("X2");
}
for (int c = 0; c < certx509.Length; c++) {
// Skip any cert that does not have the same thumbprint as token
if (certx509[c].Thumbprint.ToLower() != certthumbhex.ToLower()) {
continue;
}
X509SecurityToken tok = new X509SecurityToken(certx509[c]);
if (tok == null) {
return false;
}
for (int i = 0; i < tok.SecurityKeys.Count; i++) {
X509AsymmetricSecurityKey key = tok.SecurityKeys[i] as X509AsymmetricSecurityKey;
RSACryptoServiceProvider rsa = key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, false) as RSACryptoServiceProvider;
if (rsa == null) {
continue;
}
ret = rsa.VerifyData(uval, hash, sval);
if (ret == true) {
return ret;
}
}
}
return ret;
} catch (CryptographicException e) {
Console.WriteLine(e.ToStringDescriptive());
return false;
}
}
/// <summary>
/// Returns the certificate with which the token is encoded.
/// </summary>
/// <returns>
/// The encoding certificate.
/// </returns>
private static X509Certificate2[] GetEncodingCert() {
if (encodingcert != null) {
return encodingcert;
}
try {
// Lock for exclusive access
lock (typeof(AzureADClient)) {
XmlDocument doc = new XmlDocument();
WebRequest request =
WebRequest.Create(MetaDataEndpoint);
using (WebResponse response = request.GetResponse()) {
using (Stream responseStream = response.GetResponseStream()) {
doc.Load(responseStream);
XmlNodeList list = doc.GetElementsByTagName("X509Certificate");
encodingcert = new X509Certificate2[list.Count];
for (int i = 0; i < list.Count; i++) {
byte[] todecode_byte = Convert.FromBase64String(list[i].InnerText);
encodingcert[i] = new X509Certificate2(todecode_byte);
}
if (hash == null) {
hash = SHA256.Create();
}
}
}
}
return encodingcert;
} catch (Exception e) {
System.Diagnostics.Debug.WriteLine(e.ToStringDescriptive());
return null;
}
}
/// <summary>
/// Parses the access token into an AzureAD token.
/// </summary>
/// <param name="token">
/// The token as a string.
/// </param>
/// <param name="validate">
/// Whether to validate against time\audience.
/// </param>
/// <returns>
/// The claims as an object and null in case of failure.
/// </returns>
private AzureADClaims ParseAccessToken(string token, bool validate) {
try {
// This is the encoded JWT token split into the 3 parts
string[] strparts = token.Split('.');
// Decparts has the header and claims section decoded from JWT
string jwtHeader, jwtClaims;
string jwtb64Header, jwtb64Claims, jwtb64Sig;
byte[] jwtSig;
if (strparts.Length != 3) {
return null;
}
jwtb64Header = strparts[0];
jwtb64Claims = strparts[1];
jwtb64Sig = strparts[2];
jwtHeader = Base64URLdecode(jwtb64Header);
jwtClaims = Base64URLdecode(jwtb64Claims);
jwtSig = Base64URLdecodebyte(jwtb64Sig);
JavaScriptSerializer s1 = new JavaScriptSerializer();
AzureADClaims claimsAD = s1.Deserialize<AzureADClaims>(jwtClaims);
AzureADHeader headerAD = s1.Deserialize<AzureADHeader>(jwtHeader);
if (validate) {
// Check to see if the token is valid
// Check if its JWT and RSA encoded
if (headerAD.Typ.ToUpper() != "JWT") {
return null;
}
// Check if its JWT and RSA encoded
if (headerAD.Alg.ToUpper() != "RS256") {
return null;
}
if (string.IsNullOrEmpty(headerAD.X5t)) {
return null;
}
// Check audience to be graph
if (claimsAD.Aud.ToLower().ToLower() != GraphResource.ToLower()) {
return null;
}
// Check issuer to be sts
if (claimsAD.Iss.ToLower().IndexOf(STSName.ToLower()) != 0) {
return null;
}
// Check time validity
TimeSpan span = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
double secsnow = span.TotalSeconds;
double nbfsecs = Convert.ToDouble(claimsAD.Nbf);
double expsecs = Convert.ToDouble(claimsAD.Exp);
if ((nbfsecs - 100 > secsnow) || (secsnow > expsecs + 100)) {
return null;
}
// Validate the signature of the token
string tokUnsigned = jwtb64Header + "." + jwtb64Claims;
if (!ValidateSig(Encoding.UTF8.GetBytes(tokUnsigned), jwtSig, Base64URLdecodebyte(headerAD.X5t))) {
return null;
}
}
return claimsAD;
} catch (Exception e) {
System.Diagnostics.Debug.WriteLine(e.ToStringDescriptive());
return null;
}
}
#endregion
}
}
|