public void Authenticate(string token)
        {
            try
            {
                SimpleWebToken swt = SimpleWebToken.Parse(token, key);
                Console.WriteLine(swt.ToString());

                // Now, swt.Claims will have the list of claims
                swt.Claims.ToList().ForEach(c => Console.WriteLine("{0} ==> {1}", c.Type, c.Value));

                Thread.CurrentPrincipal = new ClaimsPrincipal(new[] { new ClaimsIdentity(swt.Claims, "SWT") });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public string GetToken(string audience, string credentials)
        {
            // TODO - Authenticate credentials here
            // TODO - Based on the audience passed in, pick the shared key from key store
            // Just hard-coding a key here
            string         key   = "qqO5yXcbijtAdYmS2Otyzeze2XQedqy+Tp37wQ3sgTQ=";
            SimpleWebToken token = new SimpleWebToken(key)
            {
                Issuer = "TokenIssuer"
            };

            token.AddClaim(ClaimTypes.Name, "jqhuman");
            token.AddClaim(ClaimTypes.Email, "*****@*****.**");
            token.AddClaim(ClaimTypes.Role, "Developer");
            token.AddClaim(ClaimTypes.Role, "Administrator");

            return(token.ToString());
        }
示例#3
0
        public static SimpleWebToken Parse(string token, string secretKey)
        {
            var items = HttpUtility.ParseQueryString(token);
            var swt   = new SimpleWebToken(secretKey);

            foreach (string key in items.AllKeys)
            {
                string item = items[key];
                switch (key)
                {
                case "Issuer": swt.Issuer = item; break;

                case "Audience": swt.Audience = item; break;

                case "ExpiresOn": swt.ExpiresOn = ulong.Parse(item); break;

                case "HMACSHA256": swt.Signature =
                    Convert.FromBase64String(item); break;

                default: swt.AddClaim(key, items[key]); break;
                }
            }

            string rawToken          = swt.ToString(); // Computes HMAC inside ToString()
            string computedSignature = HttpUtility.ParseQueryString(rawToken)
                                       ["HMACSHA256"];

            if (!computedSignature.Equals(Convert.ToBase64String(swt.Signature),
                                          StringComparison.Ordinal))
            {
                throw new SecurityTokenValidationException("Signature is invalid");
            }

            TimeSpan ts = DateTime.UtcNow - epochStart;

            if (swt.ExpiresOn < Convert.ToUInt64(ts.TotalSeconds))
            {
                throw new SecurityTokenException("Token has expired");
            }

            return(swt);
        }