acs /WebServices/Acs2WindowsPhoneSample/DPE.OAuth/Tokens/SimpleWebTokenHandler.cs

Language C# Lines 462
MD5 Hash 2da127a26e53f40636f213ddbe17efc1 Estimated Cost $9,485 (why?)
Repository https://acs.svn.codeplex.com/svn View Raw File
  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
461
462
// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace Microsoft.Samples.DPE.OAuth.Tokens
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Globalization;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    using System.Web;
    using Microsoft.IdentityModel.Claims;
    using Microsoft.IdentityModel.Tokens;
    using Microsoft.Samples.DPE.OAuth.ProtectedResource;

    public class SimpleWebTokenHandler : StringTokenHandler
    {
        public const string Namespace = "http://simple.web.token/{0}";

        public const string IssuerLabel = "Issuer";
        public const string SignatureLabel = "HMACSHA256";
        public const string AudienceLabel = "Audience";
        public const string ExpiresOnLabel = "ExpiresOn";
        public const string SignatureAlgorithmLabel = "signatureAlgorithm";
        public const string SignatureAlgorithm = "HMAC";
        public const string IdLabel = "Id";

        private SecurityTokenResolver securityTokenResolver;
        private IssuerNameRegistry issuerNameRegistry;
        private AudienceRestriction audienceRestriction;

        public SimpleWebTokenHandler()
        {            
        }

        public SecurityTokenResolver SecurityTokenResolver
        {
            get
            {
                if (this.securityTokenResolver == null && this.Configuration != null && this.Configuration.IssuerTokenResolver != null)
                {
                    this.securityTokenResolver = this.Configuration.IssuerTokenResolver;
                }

                return this.securityTokenResolver;
            }

            set
            {
                this.securityTokenResolver = value;
            }
        }

        public IssuerNameRegistry IssuerNameRegistry
        {
            get
            {
                if (this.issuerNameRegistry == null && this.Configuration != null && this.Configuration.IssuerNameRegistry != null)
                {
                    this.issuerNameRegistry = this.Configuration.IssuerNameRegistry;
                }

                return this.issuerNameRegistry;
            }

            set
            {
                this.issuerNameRegistry = value;
            }
        }

        public AudienceRestriction AudienceRestriction
        {
            get
            {
                if (this.audienceRestriction == null && this.Configuration != null && this.Configuration.AudienceRestriction != null)
                {
                    this.audienceRestriction = this.Configuration.AudienceRestriction;
                }

                return this.audienceRestriction;
            }

            set
            {
                this.audienceRestriction = value;
            }
        }

        public override Type TokenType
        {
            get
            {
                return typeof(SimpleWebToken);
            }
        }

        public override bool CanValidateToken
        {
            get { return true; }
        }

        public override string GetTokenAsString(SecurityToken token)
        {
            SimpleWebToken swt = token as SimpleWebToken;
            if (swt == null)
            {
                throw new Exception("Incorrect token type. Expected SimpleWebToken");
            }

            if (this.SecurityTokenResolver == null)
            {
                throw new InvalidOperationException("SecurityTokenResolver is not configured");
            }

            var swtSigned = SerializeToken(swt, this.SecurityTokenResolver);
            return swtSigned;
        }
        
        public override SecurityToken GetTokenFromString(string token)
        {
            // TODO: validate                        
            var items = HttpUtility.ParseQueryString(token);
            var issuer = items[IssuerLabel];
            items.Remove(IssuerLabel);
            var audience = items[AudienceLabel];
            items.Remove(AudienceLabel);
            var expiresOn = items[ExpiresOnLabel];
            items.Remove(ExpiresOnLabel);
            var id = items[IdLabel];
            items.Remove(IdLabel);
            var algorithm = items[SignatureAlgorithmLabel];
            items.Remove(SignatureAlgorithmLabel);
            
            // Treat signature differently to avoid loosing characters like '+' in the decoding
            var signature = ExtractSignature(HttpUtility.UrlDecode(token));
            items.Remove(SignatureLabel);
            
            byte[] signatureBytes = Convert.FromBase64String(signature);
            DateTime validTo = this.GetDateTimeFromExpiresOn((ulong)Convert.ToInt64(expiresOn));

            var swt = new SimpleWebToken(issuer)
            {
                Audience = audience,
                Signature = signatureBytes,
                TokenValidity = validTo - DateTime.UtcNow
            };

            if (id != null)
            {
                swt.SetId(id);
            }

            if (string.IsNullOrEmpty(algorithm))
            {
                swt.SignatureAlgorithm = algorithm;
            }

            foreach (string key in items.AllKeys)
            {
                swt.AddClaim(key, items[key]);
            }

            swt.RawToken = token;

            return swt;
        }

        public override string[] GetTokenTypeIdentifiers()
        {
            return new string[] { "http://schemas.microsoft.com/2009/11/identitymodel/tokens/swt" };
        }

        public override ClaimsIdentityCollection ValidateToken(SecurityToken token)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token is null");
            }

            if (this.SecurityTokenResolver == null)
            {
                throw new InvalidOperationException("SecurityTokenResolver is not configured");
            }

            if (this.IssuerNameRegistry == null)
            {
                throw new InvalidOperationException("IssuerNameRegistry is not configured");
            }

            if (this.AudienceRestriction == null)
            {
                throw new InvalidOperationException("AudienceRestriction is not configured");
            }

            SimpleWebToken accessToken = token as SimpleWebToken;
            if (accessToken == null)
            {
                throw new ArgumentNullException("This handler expects a SimpleWebToken");
            }

            var keyIdentifierClause = new DictionaryBasedKeyIdentifierClause(ToDictionary(accessToken));
            InMemorySymmetricSecurityKey securityKey;
            try
            {
                securityKey = (InMemorySymmetricSecurityKey)this.SecurityTokenResolver.ResolveSecurityKey(keyIdentifierClause);
            }
            catch (InvalidOperationException)
            {
                throw new SecurityTokenValidationException(string.Format(CultureInfo.InvariantCulture, "Simmetryc key was not found for the key identifier clause: Keys='{0}', Values='{1}'", string.Join(",", keyIdentifierClause.Dictionary.Keys.ToArray()), string.Join(",", keyIdentifierClause.Dictionary.Values.ToArray())));
            }

            if (!this.IsValidSignature(accessToken, securityKey.GetSymmetricKey()))
            {
                throw new SecurityTokenValidationException("Signature is invalid");
            }            

            if (this.IsExpired(accessToken))
            {
                throw new SecurityTokenException(string.Format("Token has been expired for {0} seconds already", (DateTime.UtcNow - accessToken.ValidTo).TotalSeconds));
            }

            string issuerName;
            if (!this.IsIssuerTrusted(accessToken, out issuerName))
            {
                throw new SecurityTokenException(string.Format("The Issuer {0} is not trusted", accessToken.Issuer));
            }

            if (!this.IsAudienceTrusted(accessToken))
            {
                throw new SecurityTokenException(string.Format("The audience {0} of the token is not trusted", accessToken.Audience));
            }

            var identity = this.CreateClaimsIdentity(accessToken.Parameters, issuerName);
            return new ClaimsIdentityCollection(new IClaimsIdentity[] { identity });
        }

        protected static ulong GetExpiresOn(TimeSpan secondsFromNow)
        {
            DateTime expiresDate = DateTime.UtcNow + secondsFromNow;
            TimeSpan ts = expiresDate - new DateTime(1970, 1, 1, 0, 0, 0, 0);

            return Convert.ToUInt64(ts.TotalSeconds);
        }

        protected static string GenerateSignature(string unsignedToken, byte[] signingKey)
        {
            using (HMACSHA256 hmac = new HMACSHA256(signingKey))
            {
                byte[] signatureBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(unsignedToken));
                string signature = HttpUtility.UrlEncode(Convert.ToBase64String(signatureBytes));

                return signature;
            }
        }

        protected static string SerializeToken(SimpleWebToken swt, SecurityTokenResolver tokenResolver)
        {
            StringBuilder builder = new StringBuilder(64);
            builder.Append("Id=");
            builder.Append(swt.Id);
            builder.Append('&');

            builder.Append(IssuerLabel);
            builder.Append('=');
            builder.Append(swt.Issuer);

            if (swt.Parameters.Count > 0)
            {
                builder.Append('&');
                foreach (string key in swt.Parameters.AllKeys)
                {
                    builder.Append(key);
                    builder.Append('=');
                    builder.Append(swt.Parameters[key]);
                    builder.Append('&');
                }
            }
            else
            {
                builder.Append('&');
            }

            builder.Append(ExpiresOnLabel);
            builder.Append('=');
            builder.Append(GetExpiresOn(swt.TokenValidity));

            if (!string.IsNullOrEmpty(swt.Audience))
            {
                builder.Append('&');
                builder.Append(AudienceLabel);
                builder.Append('=');
                builder.Append(swt.Audience);
            }

            builder.Append('&');
            builder.Append(SignatureAlgorithmLabel);
            builder.Append('=');
            builder.Append(SignatureAlgorithm);

            var keyIdentifierClause = new DictionaryBasedKeyIdentifierClause(ToDictionary(swt));
            InMemorySymmetricSecurityKey securityKey;
            try
            {
                securityKey = (InMemorySymmetricSecurityKey)tokenResolver.ResolveSecurityKey(keyIdentifierClause);
            }
            catch (InvalidOperationException)
            {
                throw new SecurityTokenValidationException(string.Format(CultureInfo.InvariantCulture, "Simmetryc key was not found for the key identifier clause: Keys='{0}', Values='{1}'", string.Join(",", keyIdentifierClause.Dictionary.Keys.ToArray()), string.Join(",", keyIdentifierClause.Dictionary.Values.ToArray())));
            }

            string signature = GenerateSignature(builder.ToString(), securityKey.GetSymmetricKey());
            builder.Append("&" + SignatureLabel + "=");
            builder.Append(signature);

            return builder.ToString();
        }

        protected bool IsAudienceTrusted(SimpleWebToken accessToken)
        {
            if (this.AudienceRestriction.AudienceMode == AudienceUriMode.Never)
            {
                return true;
            }

            if (!string.IsNullOrEmpty(accessToken.Audience))
            {
                return this.AudienceRestriction.AllowedAudienceUris.Contains(new Uri(accessToken.Audience));
            }

            return false;
        }

        protected bool IsExpired(SimpleWebToken accessToken)
        {
            if (accessToken.ValidTo > DateTime.UtcNow)
            {
                return false;
            }

            return true;
        }

        protected IClaimsIdentity CreateClaimsIdentity(NameValueCollection values, string issuer)
        {
            var identity = new ClaimsIdentity("SimpleWebToken");

            foreach (var key in values.AllKeys)
            {
                Uri claimType;
                bool validUri = Uri.TryCreate(key, UriKind.Absolute, out claimType);
                if (!validUri)
                {
                    claimType = new Uri(String.Format(Namespace, key));
                }

                var multivalues = values[key].Split(',');
                foreach (var value in multivalues)
                {
                    identity.Claims.Add(
                        new Claim(
                            claimType.ToString(),
                            value,
                            ClaimValueTypes.String,
                            issuer));
                }
            }

            return identity;
        }

        protected bool IsValidSignature(SimpleWebToken token, byte[] signingKey)
        {
            var unsignedToken = this.GetUnsignedToken(token.RawToken);
            if (string.IsNullOrEmpty(unsignedToken))
            {
                return false;
            }

            var localSignature = GenerateSignature(unsignedToken, signingKey);
            var incomingSignature = HttpUtility.UrlEncode(Convert.ToBase64String(token.Signature));

            return localSignature.Equals(incomingSignature, StringComparison.Ordinal);
        }        

        private static string ExtractSignature(string swtSigned)
        {
            var parts = swtSigned.Split(new string[] { string.Format("&{0}=", SignatureLabel) }, StringSplitOptions.None);
            var signature = Uri.UnescapeDataString(parts[1]);

            return signature;
        }

        private static IDictionary<string, string> ToDictionary(SimpleWebToken token)
        {
            var dictionary = new Dictionary<string, string>
            {
                { "Issuer", token.Issuer },
                { "Audience", token.Audience }                
            };

            return dictionary;
        }
        
        private DateTime GetDateTimeFromExpiresOn(ulong seconds)
        {
            var start = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            var expiresOn = start.AddSeconds(seconds);

            return expiresOn;
        }

        private bool IsIssuerTrusted(SimpleWebToken accessToken, out string issuerName)
        {
            issuerName = null;
            if (!string.IsNullOrEmpty(accessToken.Issuer))
            {
                if (this.IssuerNameRegistry != null)
                {
                    issuerName = this.IssuerNameRegistry.GetIssuerName(accessToken);
                    if (!string.IsNullOrEmpty(issuerName))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        private string GetUnsignedToken(string swtSigned)
        {
            // Assume signature is at the end of token
            var signaturePosition = swtSigned.IndexOf(string.Format("&{0}=", SignatureLabel));
            if (signaturePosition <= 0)
            {
                return null;
            }

            var unsigned = swtSigned.Substring(0, signaturePosition);

            return unsigned;
        }        
    }
}
Back to Top