public void NewTokenWithArgs()
        {
            var args = new Dictionary<string, string>
            {
                {"alfa", "beta"}, 
                {"http://unittest-ip.com/alfa", "fisk & fugl"}
            };

            const string issuer = "http://unittest-ip.com/";
            const string audience = "http://unittest-rt.com/";
            var expiresOn = new DateTime(2034, 4, 7, 23, 12, 34, DateTimeKind.Utc);
            const string signingKey = "nh0BPopBTc7MAzviohoUbWNhO6NlV+LYm+sXOTPULxk=";

            var swt = new SimpleWebToken(issuer, audience, expiresOn, signingKey, args);
            Assert.AreEqual(expiresOn, swt.ExpiresOn);
            Assert.AreEqual(issuer, swt.Issuer);
            Assert.AreEqual(audience, swt.Audience);
            Assert.IsNotNull(swt.RawToken);
            Assert.IsNotNull(swt.Signature);
            Assert.IsTrue(swt.ValidateSignature(signingKey));
            foreach (var item in args)
                Assert.AreEqual(item.Value, swt[item.Key]);
            Assert.AreEqual(2, swt.Keys.Count());
            Assert.IsTrue(swt.Keys.Contains("alfa"));
            Assert.IsTrue(swt.Keys.Contains("http://unittest-ip.com/alfa"));
        }
        public void ToStringReturnsCorrectResult(string[] keysAndValues, string expected)
        {
            var claims = keysAndValues
                .Select(s => s.Split('|'))
                .Select(s => new Claim(s[0], s[1]))
                .ToArray();

            var sut = new SimpleWebToken(claims);
            var actual = sut.ToString();
            Assert.Equal(expected, actual);
        }
        public void ToStringShouldBeRight(string[] action, string expected)
        {
            //var expected = new[]
            //    {
            //        new Claim("foo", "bar")
            //    };
            var claims = action.Select(s => s.Split('|')).Select(a => new Claim(a[0], a[1])).ToArray();

            var sut = new SimpleWebToken(claims);

            Assert.Equal(expected, sut.ToString());
        }
        public void SutYieldInjectedClaims()
        {
            var expected = new[]
            {
                new Claim("foo", "bar"),
                new Claim("baz", "qux"),
                new Claim("quux", "corge")
            };

            var sut = new SimpleWebToken(expected);

            Assert.True(expected.SequenceEqual(sut));
            Assert.True(expected.Cast<object>().SequenceEqual(((IEnumerable)sut).OfType<object>()));
        }
        private static SimpleWebToken CreateSimpleWebToken(string issuer, string scope, TimeSpan validity, NameValueCollection additionalInfo)
        {
            var swt = new SimpleWebToken(issuer) { Audience = scope, TokenValidity = validity };

            if (additionalInfo != null)
            {
                foreach (string key in additionalInfo.AllKeys)
                {
                    swt.Parameters.Add(key, additionalInfo[key]);
                }
            }

            return swt;
        }
        public void YieldEnumeratorOfClaims()
        {
            var expected = new[]
                {
                    new Claim("foo", "bar"),
                    new Claim("queue", "qux"),
                    new Claim("Rafael", "Ricardo")
                };

            var sut = new SimpleWebToken(expected);

            Assert.True(expected.SequenceEqual(sut));
            Assert.True(expected.Cast<object>().SequenceEqual(sut.OfType<object>()));
        }
        public void TryParsevalidStringReturnsCorrectResult(string[] keysAndValues)
        {
            var expected = keysAndValues
               .Select(s => s.Split('|'))
               .Select(s => new Claim(s[0], s[1]))
               .ToArray();

            var tokenString = new SimpleWebToken(expected).ToString();
            SimpleWebToken actual;
            var isValid = SimpleWebToken.TryParse(tokenString, out actual);
            Assert.True(isValid, "Token string was not valid");

            Assert.True(expected.SequenceEqual(actual, new ClaimComparer()));
        }
        public void NewToken()
        {
            const string issuer = "http://unittest-ip.com/";
            const string audience = "http://unittest-rt.com/";
            var expiresOn = new DateTime(2034, 4, 7, 23, 12, 34, DateTimeKind.Utc);
            const string signingKey = "nh0BPopBTc7MAzviohoUbWNhO6NlV+LYm+sXOTPULxk=";

            var swt = new SimpleWebToken(issuer, audience, expiresOn, signingKey);
            Assert.AreEqual(expiresOn, swt.ExpiresOn);
            Assert.AreEqual(issuer, swt.Issuer);
            Assert.AreEqual(audience, swt.Audience);
            Assert.IsNotNull(swt.RawToken);
            Assert.IsNotNull(swt.Signature);
            Assert.IsTrue(swt.ValidateSignature(signingKey));
            Assert.AreEqual(0, swt.Keys.Count());
        }
        private static string CreateSwtToken()
        {
            var signingKey = "wAVkldQiFypTQ+kdNdGWCYCHRcee8XmXxOvgmak8vSY=";
            var audience = "http://websample";
            var issuer = "http://self";

            var token = new SimpleWebToken(issuer, audience, Convert.FromBase64String(signingKey));

            token.AddClaim(ClaimTypes.Name, "dominick");
            token.AddClaim(ClaimTypes.Email, "[email protected]");
            token.AddClaim(ClaimTypes.Role, "Users");
            token.AddClaim(ClaimTypes.Role, "Administrators");
            token.AddClaim("simple", "test");

            return token.ToString();
        }
 public void FromValidEncoded()
 {
     const string tokenString = "http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=upwJyUGTUPWMEiU3ds61jcsJUeUFjRza6sNEcdyNYnw%3d&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=uri%3aWindowsLiveID&Audience=http%3a%2f%2fnoisesentinel-dev-adminapi.azurewebsites.net%2f&ExpiresOn=1356650451&Issuer=https%3a%2f%2fbruelandkjaer.accesscontrol.windows.net%2f&HMACSHA256=npM6PtfuNUtG6EJ1gpS0s9rVvEx%2buP4UIXe3GB1t4CM%3d";
     var swt = new SimpleWebToken(tokenString);
     Assert.AreEqual(tokenString, swt.RawToken);
     Assert.AreEqual(new DateTime(2012, 12, 27, 23, 20, 51, DateTimeKind.Utc), swt.ExpiresOn);
     Assert.AreEqual("https://bruelandkjaer.accesscontrol.windows.net/", swt.Issuer);
     Assert.AreEqual("http://noisesentinel-dev-adminapi.azurewebsites.net/", swt.Audience);
     Assert.AreEqual("uri:WindowsLiveID", swt["http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider"]);
     Assert.AreEqual("upwJyUGTUPWMEiU3ds61jcsJUeUFjRza6sNEcdyNYnw=", swt["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"]);
     Assert.AreEqual("npM6PtfuNUtG6EJ1gpS0s9rVvEx+uP4UIXe3GB1t4CM=", swt.Signature);
     Assert.IsTrue(swt.ValidateSignature("eP+VgZq3YVUXSDt71lKnCRoxdoGngCT9WR4vTprH9TY="));
     Assert.IsFalse(swt.ValidateSignature("nh0BPopBTc7MAzviohoUbWNhO6NlV+LYm+sXOTPULxk="));
     Assert.IsNotNull(swt);
     Assert.AreEqual(2, swt.Keys.Count());
     Assert.IsTrue(swt.Keys.Contains("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider"));
     Assert.IsTrue(swt.Keys.Contains("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"));
 }
        private static string SerializeToken(SimpleWebToken accessToken, SecurityTokenHandlerCollection handlers)
        {
            if (handlers.CanWriteToken(accessToken))
            {
                string token = String.Empty;
                using (var sw = new StringWriter())
                {
                    var writer = new XmlTextWriter(sw);
                    handlers.WriteToken(writer, accessToken);

                    // remove the envelope <stringToken>
                    var envelope = sw.ToString();
                    token = XElement.Parse(envelope).Value;
                }

                return token;
            }

            return null;
        }
        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);
        }        
Example #13
0
        public void Test3()
        {
            string testKey = "ZncEZCBioztYEE3iC6dSnv+lJC4NmFX7Ns5pDgPKCwU=";

            NameValueCollection claims = new NameValueCollection();

            claims.Add("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "robblackwell");
            claims.Add("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "https://clazure.accesscontrol.windows.net/");

            SimpleWebToken swt = new SimpleWebToken("https://clazure.accesscontrol.windows.net/",
                    "http://www.robblackwell.org.uk/", 1331740071, claims);

            swt.Sign(testKey);

            Assert.IsTrue(swt.CheckSignature(testKey));
        }
        /// <summary>
        /// Check if the user is authenticated with a valid token
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        protected static bool IsAuthenticated(HttpContext context, out SimpleWebToken swttoken)
        {
            IClaimsIdentity currentIdentiy = context.User.Identity as IClaimsIdentity;
            IClaimsPrincipal incomingPrincipal = context.User as IClaimsPrincipal;

            //if (!incomingPrincipal.Identity.IsAuthenticated)
            //{
            if (new cf.Identity.CfIdentityInflater().TryGetSwtClaimsIdentity(out currentIdentiy, out swttoken))
            {
                incomingPrincipal.Identities[0] = currentIdentiy;
            }
            //}

            return incomingPrincipal.Identity.IsAuthenticated;
        }
        private static void CheckPrinciple(SimpleWebToken swt)
        {
            IClaimsPrincipal principle = swt.ToPrinciple(nameClaimType: ClaimTypes.NameIdentifier);
            Assert.IsNotNull(principle);

            IClaimsIdentity identity = principle.Identity as IClaimsIdentity;
            Assert.IsNotNull(identity);

            if (identity != null)
            {
                foreach (var claim in identity.Claims)
                {
                    System.Console.WriteLine(string.Format("Claim Type: {0}, Claim Value: {1}", claim.ClaimType, claim.Value));
                }
            }
        }
        protected bool IsExpired(SimpleWebToken accessToken)
        {
            if (accessToken.ValidTo > DateTime.UtcNow)
            {
                return false;
            }

            return true;
        }
        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 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();
        }
        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;
        }
 private void WrapSWT(NameValueCollection collection, SimpleWebToken token, bool deflate)
 {
     var rawToken = token.RawToken;
     if (deflate)
     {
         var zipped = this.ZipStr(rawToken);
         rawToken = Convert.ToBase64String(zipped);
         collection["wrap_deflated"] = "true";
     }
     collection["wrap_access_token"] = HttpUtility.UrlEncode(rawToken);
     var seconds = Convert.ToInt32((token.ValidTo - token.ValidFrom).TotalSeconds);
     collection["wrap_access_token_expires_in"] = seconds.ToString();
 }
        private static IDictionary<string, string> ToDictionary(SimpleWebToken token)
        {
            var dictionary = new Dictionary<string, string>
            {
                { "Issuer", token.Issuer },
                { "Audience", token.Audience }                
            };

            return dictionary;
        }
        public void TestTokenConstructor()
        {
            string testKey = "ZncEZCBioztYEE3iC6dSnv+lJC4NmFX7Ns5pDgPKCwU=";
            string trustedIssuer = "https://clazure.accesscontrol.windows.net/";
            string expectedAudience = "http://www.robblackwell.org.uk/";

            NameValueCollection claims = new NameValueCollection();

            claims.Add("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "robblackwell");
            claims.Add("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "https://clazure.accesscontrol.windows.net/");

            SimpleWebToken swt = new SimpleWebToken("https://clazure.accesscontrol.windows.net/",
                    "http://www.robblackwell.org.uk/", DateTime.UtcNow.AddHours(1), claims);

            swt.Sign(testKey);

            CheckToken(swt, testKey, trustedIssuer, expectedAudience);
            CheckPrinciple(swt);
        }
        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 static void CheckToken(SimpleWebToken swt, string testKey, string trustedIssuer, string expectedAudience)
 {
     SimpleWebTokenValidationResult validationResult = SimpleWebToken.Validate(swt, testKey, trustedIssuer, expectedAudience);
     Assert.IsTrue(validationResult == SimpleWebTokenValidationResult.Valid, string.Format("Invalid Token: {0}", validationResult.ToString()));
 }
 public void SutIsIteratorOfClaims()
 {
     var sut = new SimpleWebToken();
     Assert.IsAssignableFrom<IEnumerable<Claim>>(sut);
 }