Пример #1
0
        public void CreateTokenAndParseEncodedMultipleClaims()
        {
            var handler = new SimpleWebTokenHandler();

            string key;
            var    token       = this.GetToken(out key);
            var    tokenString = TokenToString(token);
            var    signedToken = handler.ReadToken(new XmlTextReader(new StringReader(tokenString)));

            handler.Configuration = new SecurityTokenHandlerConfiguration();

            var registry = new WebTokenIssuerNameRegistry();

            //I think there is currently a bug in this issuer as this really doesn't make sense to me
            registry.AddTrustedIssuer("http://www.thinktecture.com", "TestIssuerName");

            handler.Configuration.IssuerNameRegistry = registry;
            handler.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://www.thinktecture.com/"));

            var tokenResolver = new WebTokenIssuerTokenResolver();

            tokenResolver.AddSigningKey("http://www.thinktecture.com", key);
            handler.Configuration.IssuerTokenResolver = tokenResolver;

            var claims = handler.ValidateToken(signedToken);

            Assert.IsTrue(claims[0].Claims.Count == 3);
            Assert.IsTrue(claims[0].Claims[0].Value == this.Claims()[0].Value);
            Assert.IsTrue(claims[0].Claims[1].Value == this.Claims()[1].Value);
            Assert.IsTrue(claims[0].Claims[2].Value == this.Claims()[2].Value);
        }
Пример #2
0
        private static void ValidateSwtToken(string tokenString)
        {
            var configuration = new SecurityTokenHandlerConfiguration();
            var validationKey = new InMemorySymmetricSecurityKey(Convert.FromBase64String(signingKey));

            // audience validation
            configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(realm));

            // signature & issuer validation
            var resolverTable = new Dictionary <string, IList <SecurityKey> >
            {
                { issuerUri, new SecurityKey[] { validationKey } }
            };

            configuration.IssuerTokenResolver = new NamedKeyIssuerTokenResolver(resolverTable);

            var handler = new SimpleWebTokenHandler();

            handler.Configuration = configuration;

            var token = handler.ReadToken(tokenString);
            var ids   = handler.ValidateToken(token);

            "\n\nValidated Claims:".ConsoleYellow();
            foreach (var claim in ids.First().Claims)
            {
                Console.WriteLine("{0}\n {1}\n", claim.Type, claim.Value);
            }
        }
Пример #3
0
        public void CreateTokenAndParseEncodedMultipleClaims()
        {
            var handler = new SimpleWebTokenHandler();

            byte[] key         = GetKey();
            var    token       = this.CreateToken(key);
            var    tokenString = TokenToString(token);
            var    signedToken = handler.ReadToken(new XmlTextReader(new StringReader(tokenString)));

            handler.Configuration = new SecurityTokenHandlerConfiguration();

            var symmetricKey = new InMemorySymmetricSecurityKey(key);

            handler.Configuration.AudienceRestriction.AllowedAudienceUris.Add(
                new Uri("http://audience"));

            var resolverTable = new Dictionary <string, IList <SecurityKey> >
            {
                { "http://issuer", new SecurityKey[] { symmetricKey } }
            };

            handler.Configuration.IssuerTokenResolver = new NamedKeyIssuerTokenResolver(resolverTable);

            var ids = handler.ValidateToken(signedToken);
            var id  = ids.FirstOrDefault();

            Assert.IsNotNull(id);

            var testClaims = GetClaims();

            Assert.IsTrue(id.Claims.Count() == 3);
            Assert.IsTrue(id.HasClaim(testClaims[0].Type, testClaims[0].Value));
            Assert.IsTrue(id.HasClaim(testClaims[1].Type, testClaims[1].Value));
            Assert.IsTrue(id.HasClaim(testClaims[2].Type, testClaims[2].Value));
        }
Пример #4
0
        /// <summary>
        /// This method parses the incoming token and validates it.
        /// </summary>
        /// <param name="accessToken">The incoming access token.</param>
        /// <param name="error">This out paramter is set if any error occurs.</param>
        /// <returns>True on success, False on error.</returns>
        protected bool ReadAndValidateToken(string accessToken, out ResourceAccessErrorResponse error)
        {
            bool tokenValid = false;

            error = null;

            SecurityToken            token = null;
            ClaimsIdentityCollection claimsIdentityCollection = null;

            try
            {
                var handler = new SimpleWebTokenHandler(_issuer, _tokenSigningKey);

                // read the token
                token = handler.ReadToken(accessToken);

                // validate the token
                claimsIdentityCollection = handler.ValidateToken(token, _realm);

                // create a claims Principal from the token
                var claimsPrincipal = ClaimsPrincipal.CreateFromIdentities(claimsIdentityCollection);
                if (claimsPrincipal != null)
                {
                    tokenValid = true;

                    // push it through the pipeline
                    foreach (var step in authenticationPipeline)
                    {
                        claimsPrincipal = step.Authenticate(token, claimsPrincipal);
                    }

                    // assign to threads
                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.User = claimsPrincipal;
                    }
                    Thread.CurrentPrincipal = claimsPrincipal;
                }
            }
            catch (InvalidTokenReceivedException ex)
            {
                error = new ResourceAccessErrorResponse(_realm, ex.ErrorCode, ex.ErrorDescription);
            }
            catch (ExpiredTokenReceivedException ex)
            {
                error = new ResourceAccessErrorResponse(_realm, ex.ErrorCode, ex.ErrorDescription);
            }
            catch (Exception)
            {
                error = new ResourceAccessErrorResponse(_realm, "SWT401", "Token validation failed");
            }

            return(tokenValid);
        }
        private SimpleWebToken ResponseToSimpleWebToken(string response)
        {
            var tokenString =
                Uri.UnescapeDataString(
                    response.Split('&')
                    .Single(value => value.StartsWith("wrap_access_token=", StringComparison.OrdinalIgnoreCase))
                    .Split('=')[1]);

            var handler = new SimpleWebTokenHandler();
            var swt     = handler.ReadToken(tokenString) as SimpleWebToken;

            return(swt);
        }
Пример #6
0
        private string GetRawToken()
        {
            string rawToken     = OAuthClientModule.GetAccessToken(this._realm, false);
            var    tokenHandler = new SimpleWebTokenHandler();
            var    token        = tokenHandler.ReadToken(Encoding.ASCII.GetString(Convert.FromBase64String(rawToken)));

            if (DateTime.Compare(token.ValidTo, DateTime.UtcNow.Add(_skew)) <= 0)
            {
                rawToken = OAuthClientModule.GetAccessToken(this._realm, true);
            }

            return(rawToken);
        }