Пример #1
0
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpRequest httpRequest = HttpContext.Current.Request;

            string SecretKey = WebConfigurationManager.AppSettings["SecretKey"].ToString();

            string cookieName = WebConfigurationManager.AppSettings["CookieName"].ToString();

            if (httpRequest.Cookies[cookieName] != null)
            {
                JwtObject jwtObject = JWT.Decode <JwtObject>(Convert.ToString(httpRequest.Cookies[cookieName].Value),
                                                             Encoding.UTF8.GetBytes(SecretKey), JwsAlgorithm.HS512);

                string[] roles = jwtObject.Role.Split(new char[] { ',' });

                Claim[] claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, jwtObject.Account),
                    new Claim(ClaimTypes.NameIdentifier, jwtObject.Account)
                };

                var claimsIdentity = new ClaimsIdentity(claims, cookieName);
                claimsIdentity.AddClaim(new Claim(@"http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
                                                  "My Identity", @"http://www.w3.org/2001/XMLSchena#string"));

                HttpContext.Current.User = new GenericPrincipal(claimsIdentity, roles);
                Thread.CurrentPrincipal  = HttpContext.Current.User;
            }
        }
Пример #2
0
        //撰寫權限驗證前執行的動作
        //在此用於設定角色(Role)
        protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
        {
            //接收請求資料
            HttpRequest httpRequest = HttpContext.Current.Request;
            //設定JWT密鑰
            string SecretKey = WebConfigurationManager.AppSettings["SecretKey"].ToString();
            //設定Cookie名稱
            string cookieName = WebConfigurationManager.AppSettings["CookieName"].ToString();

            //檢查coockie內是否存放TOKEN
            if (httpRequest.Cookies[cookieName] != null)
            {
                //將TOKEN還原
                JwtObject jwtObject = JWT.Decode <JwtObject>(Convert.ToString(httpRequest.Cookies[cookieName].Value), Encoding.UTF8.GetBytes(SecretKey), JwsAlgorithm.HS512);
                //將使用者角色資料取出,並分割成陣列
                string[] roles = jwtObject.Role.Split(new char[] { ',' });
                //自行建立Identity取代HttpContext.Current.User的Identity
                //將資料塞進Claim內做設計
                Claim[] claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, jwtObject.Account),
                    new Claim(ClaimTypes.NameIdentifier, jwtObject.Account)
                };
                var claimsIdentity = new ClaimsIdentity(claims, cookieName);
                //加入identityprovider這個Calim使得反仿冒語彙@Html.AntiForgeryToken()能通過
                claimsIdentity.AddClaim(new Claim(@"http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "My Identity", @"http://www.w3.org/2001/XMLSchema#string"));
                //指派角色到目前這個HttpContext的User物件去
                HttpContext.Current.User = new GenericPrincipal(claimsIdentity, roles);
                Thread.CurrentPrincipal  = HttpContext.Current.User;
            }
        }
Пример #3
0
        /// <inheritsdoc />
        public override Jwk WrapKey(Jwk?staticKey, JwtObject header, Span <byte> destination)
        {
            if (_disposed)
            {
                ThrowHelper.ThrowObjectDisposedException(GetType());
            }

            var cek = CreateSymmetricKey(EncryptionAlgorithm, staticKey);

#if !NETSTANDARD2_0 && !NET461
            if (!_rsa.TryEncrypt(cek.AsSpan(), destination, _padding, out int bytesWritten) || bytesWritten != destination.Length)
            {
                ThrowHelper.ThrowCryptographicException_KeyWrapFailed();
            }
#else
            var result = _rsa.Encrypt(cek.AsSpan().ToArray(), _padding);
            if (destination.Length < result.Length)
            {
                ThrowHelper.ThrowCryptographicException_KeyWrapFailed();
            }

            result.CopyTo(destination);
#endif

            return(cek);
        }
Пример #4
0
        public virtual Jwk WrapKey(KeyWrapper wrapper, Jwk keyToWrap, out JwtObject header)
        {
            var destination = new byte[wrapper.GetKeyWrapSize()];

            header = new JwtObject();
            var cek = wrapper.WrapKey(keyToWrap, header, destination);

            return(cek);
        }
Пример #5
0
        public void WrapKey_Failure()
        {
            var keyEncryptionKey = SymmetricJwk.GenerateKey(128);
            var wrapper          = new AesKeyWrapper(keyEncryptionKey, EncryptionAlgorithm.Aes256CbcHmacSha512, KeyManagementAlgorithm.Aes128KW);
            var destination      = new byte[0];
            var header           = new JwtObject();

            Assert.Throws <ArgumentException>(() => wrapper.WrapKey(null, header, destination));

            Assert.Equal(0, header.Count);
        }
Пример #6
0
        public void WrapKey_Failure()
        {
            var keyEncryptionKey = SymmetricJwk.GenerateKey(256);
            var contentEncryptionKey = SymmetricJwk.GenerateKey(256);
            var wrapper = new AesGcmKeyWrapper(keyEncryptionKey, EncryptionAlgorithm.Aes256Gcm, KeyManagementAlgorithm.Aes256GcmKW);
            var destination = new byte[0];
            var header = new JwtObject();
            Assert.Throws<ArgumentException>(() => wrapper.WrapKey(contentEncryptionKey, header, destination));

            Assert.Equal(0, header.Count);
        }
Пример #7
0
        public override Jwk WrapKey(Jwk?staticKey, JwtObject header, Span <byte> destination)
        {
            if (staticKey != null)
            {
                ThrowHelper.ThrowArgumentException_StaticKeyNotSupported();
            }

            ReadOnlySpan <byte> bytes = Key.AsSpan();

            return(SymmetricJwk.FromSpan(bytes, false));
        }
Пример #8
0
        public string GenerateToken(string Account, string Name)
        {
            string secret  = "Guestbook";
            var    payload = new JwtObject
            {
                Account = Account,
                Name    = Name,
                Exp     = DateTime.Now.AddSeconds(Convert.ToInt32("1200")).ToString()
            };
            var token = JWT.Encode(payload, Encoding.UTF8.GetBytes(secret), JwsAlgorithm.HS512);

            return(token);
        }
Пример #9
0
        public void WrapKey_Failure()
        {
            var keyEncryptionKey = RsaJwk.GenerateKey(2048, true);
            var wrapper          = new RsaKeyWrapper(keyEncryptionKey, EncryptionAlgorithm.Aes256CbcHmacSha512, KeyManagementAlgorithm.RsaOaep);
            var destination      = new byte[0];
            var header           = new JwtObject();

            Assert.Throws <CryptographicException>(() => wrapper.WrapKey(null, header, destination));
            wrapper.Dispose();
            Assert.Throws <ObjectDisposedException>(() => wrapper.WrapKey(null, header, destination));

            Assert.Equal(0, header.Count);
        }
Пример #10
0
        public void Wrap_Rfc7518_Appendix_C()
        {
            var kwp    = new EcdhKeyWrapper(_bobKey, EncryptionAlgorithm.Aes128Gcm, KeyManagementAlgorithm.EcdhEs);
            var header = new JwtObject();

            header.Add(new JwtProperty(HeaderParameters.ApuUtf8, Base64Url.Encode("Alice")));
            header.Add(new JwtProperty(HeaderParameters.ApvUtf8, Base64Url.Encode("Bob")));

            var cek = kwp.WrapKey(_aliceKey, header, null);

            var expected = new byte[] { 86, 170, 141, 234, 248, 35, 109, 32, 92, 34, 40, 205, 113, 167, 16, 26 };

            Assert.Equal(expected, cek.AsSpan().ToArray());
        }
Пример #11
0
        public void WrapKey_Failure()
        {
            var keyEncryptionKey = ECJwk.GenerateKey(EllipticalCurve.P256, true);
            var wrapper          = new EcdhKeyWrapper(keyEncryptionKey, EncryptionAlgorithm.Aes256CbcHmacSha512, KeyManagementAlgorithm.EcdhEs);
            var destination      = new byte[0];
            var header           = new JwtObject();
            Jwk cek = null;

            Assert.Throws <ArgumentNullException>(() => wrapper.WrapKey(null, null, destination));
            wrapper.Dispose();
            Assert.Throws <ObjectDisposedException>(() => wrapper.WrapKey(null, header, destination));

            Assert.Equal(0, header.Count);
            Assert.Null(cek);
        }
Пример #12
0
        public static JwtObject ToJwtObject(JObject json)
        {
            var jwtObject = new JwtObject();

            foreach (var property in json.Properties())
            {
                JwtProperty jwtProperty;
                switch (property.Value.Type)
                {
                case JTokenType.Object:
                    jwtProperty = new JwtProperty(property.Name, ToJwtObject(property.Value.Value <JObject>()));
                    break;

                case JTokenType.Array:
                    jwtProperty = new JwtProperty(property.Name, ToJwtArray(property.Value.Value <JArray>()));
                    break;

                case JTokenType.Integer:
                    jwtProperty = new JwtProperty(property.Name, property.Value.Value <long>());
                    break;

                case JTokenType.Float:
                    jwtProperty = new JwtProperty(property.Name, property.Value.Value <double>());
                    break;

                case JTokenType.String:
                    jwtProperty = new JwtProperty(property.Name, property.Value.Value <string>());
                    break;

                case JTokenType.Boolean:
                    jwtProperty = new JwtProperty(property.Name, property.Value.Value <bool>());
                    break;

                case JTokenType.Null:
                    jwtProperty = new JwtProperty(property.Name);
                    break;

                default:
                    throw new NotSupportedException();
                }

                jwtObject.Add(jwtProperty);
            }

            return(jwtObject);
        }
Пример #13
0
        /// <inheritsdoc />
        public override Jwk WrapKey(Jwk?staticKey, JwtObject header, Span <byte> destination)
        {
            if (_disposed)
            {
                ThrowHelper.ThrowObjectDisposedException(GetType());
            }

            var         cek   = CreateSymmetricKey(EncryptionAlgorithm, staticKey);
            Span <byte> nonce = stackalloc byte[IVSize];
            Span <byte> tag   = stackalloc byte[TagSize];

            using (var aesGcm = new AesGcm(Key.AsSpan()))
            {
                aesGcm.Encrypt(nonce, cek.AsSpan(), destination, tag);

                header.Add(new JwtProperty(HeaderParameters.IVUtf8, Base64Url.Encode(nonce)));
                header.Add(new JwtProperty(HeaderParameters.TagUtf8, Base64Url.Encode(tag)));
            }

            return(cek);
        }
Пример #14
0
        public void Unwrap2()
        {
            var kwp = new EcdhKeyWrapper(_bobKey, EncryptionAlgorithm.Aes128CbcHmacSha256, KeyManagementAlgorithm.EcdhEsAes128KW);

            byte[] wrappedKey = new byte[kwp.GetKeyWrapSize()];
            var    header     = new JwtObject();

            header.Add(new JwtProperty(HeaderParameters.ApuUtf8, Base64Url.Encode("Alice")));
            header.Add(new JwtProperty(HeaderParameters.ApvUtf8, Base64Url.Encode("Bob")));

            var cek = kwp.WrapKey(_aliceKey, header, wrappedKey);

            var kuwp      = new EcdhKeyUnwrapper(_bobKey, EncryptionAlgorithm.Aes128CbcHmacSha256, KeyManagementAlgorithm.EcdhEsAes128KW);
            var apu       = Encoding.UTF8.GetString(Base64Url.Encode("Alice"));;
            var apv       = Encoding.UTF8.GetString(Base64Url.Encode("Bob"));
            var epk       = ((JwtObject)header[HeaderParameters.EpkUtf8].Value).ToString();
            var jwtHeader = JwtHeader.FromJson($"{{\"apu\":\"{apu}\",\"apv\":\"{apv}\",\"epk\":{epk}}}");

            byte[] unwrappedKey = new byte[kuwp.GetKeyUnwrapSize(wrappedKey.Length)];
            var    unwrapped    = kuwp.TryUnwrapKey(wrappedKey, unwrappedKey, jwtHeader, out int bytesWritten);

            Assert.True(unwrapped);
        }
Пример #15
0
        internal static JwtHeader ReadJwtHeaderSlow(ref Utf8JsonReader reader)
        {
            var current = new JwtObject(3);
            var header  = new JwtHeader(current);

            while (reader.Read())
            {
                if (!(reader.TokenType is JsonTokenType.PropertyName))
                {
                    break;
                }

                if (reader.ValueTextEquals(HeaderParameters.AlgUtf8) && reader.Read())
                {
                    if (!(reader.TokenType is JsonTokenType.String))
                    {
                        break;
                    }

                    var alg = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
                    if (SignatureAlgorithm.TryParse(alg, out var signatureAlgorithm))
                    {
                        header.SignatureAlgorithm = signatureAlgorithm;
                    }
                    else if (KeyManagementAlgorithm.TryParse(alg, out var keyManagementAlgorithm))
                    {
                        header.KeyManagementAlgorithm = keyManagementAlgorithm;
                    }
                    else if (SignatureAlgorithm.TryParseSlow(ref reader, out signatureAlgorithm))
                    {
                        header.SignatureAlgorithm = signatureAlgorithm;
                    }
                    else if (KeyManagementAlgorithm.TryParseSlow(ref reader, out keyManagementAlgorithm))
                    {
                        header.KeyManagementAlgorithm = keyManagementAlgorithm;
                    }
                    else
                    {
                        // TODO : Fix when the Utf8JsonReader will allow
                        // to read an unescaped string without allocating a string
                        current.Add(new JwtProperty(WellKnownProperty.Alg, Encoding.UTF8.GetBytes(reader.GetString())));
                    }
                }
                else if (reader.ValueTextEquals(HeaderParameters.EncUtf8) && reader.Read())
                {
                    if (!(reader.TokenType is JsonTokenType.String))
                    {
                        break;
                    }

                    var enc = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
                    if (EncryptionAlgorithm.TryParse(enc, out var encryptionAlgorithm))
                    {
                        header.EncryptionAlgorithm = encryptionAlgorithm;
                    }
                    else if (EncryptionAlgorithm.TryParseSlow(ref reader, out encryptionAlgorithm))
                    {
                        header.EncryptionAlgorithm = encryptionAlgorithm;
                    }
                    else
                    {
                        // TODO : Fix when the Utf8JsonReader will allow
                        // to read an unescaped string without allocating a string
                        current.Add(new JwtProperty(WellKnownProperty.Enc, Encoding.UTF8.GetBytes(reader.GetString())));
                    }
                }
                else if (reader.ValueTextEquals(HeaderParameters.CtyUtf8) && reader.Read())
                {
                    if (!(reader.TokenType is JsonTokenType.String))
                    {
                        break;
                    }

                    current.Add(new JwtProperty(WellKnownProperty.Cty, Encoding.UTF8.GetBytes(reader.GetString())));
                }
                else if (reader.ValueTextEquals(HeaderParameters.TypUtf8) && reader.Read())
                {
                    if (!(reader.TokenType is JsonTokenType.String))
                    {
                        break;
                    }

                    current.Add(new JwtProperty(WellKnownProperty.Typ, Encoding.UTF8.GetBytes(reader.GetString())));
                }
                else if (reader.ValueTextEquals(HeaderParameters.KidUtf8) && reader.Read())
                {
                    if (!(reader.TokenType is JsonTokenType.String))
                    {
                        break;
                    }

                    current.Add(new JwtProperty(WellKnownProperty.Kid, reader.GetString()));
                }
                else if (reader.ValueTextEquals(HeaderParameters.ZipUtf8) && reader.Read())
                {
                    if (!(reader.TokenType is JsonTokenType.String))
                    {
                        break;
                    }

                    var zip = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
                    if (CompressionAlgorithm.TryParse(zip, out var compressionAlgorithm))
                    {
                        current.Add(new JwtProperty(compressionAlgorithm));
                    }
                    else if (CompressionAlgorithm.TryParseSlow(ref reader, out compressionAlgorithm))
                    {
                        current.Add(new JwtProperty(compressionAlgorithm));
                    }
                    else
                    {
                        // TODO : Fix when the Utf8JsonReader will allow
                        // to read an unescaped string without allocating a string
                        current.Add(new JwtProperty(WellKnownProperty.Zip, Encoding.UTF8.GetBytes(reader.GetString())));
                    }
                }
                else
                {
                    var name = reader.GetString();
                    reader.Read();
                    switch (reader.TokenType)
                    {
                    case JsonTokenType.StartObject:
                        current.Add(name, JsonParser.ReadJsonObject(ref reader));
                        break;

                    case JsonTokenType.StartArray:
                        current.Add(name, JsonParser.ReadJsonArray(ref reader));
                        break;

                    case JsonTokenType.String:
                        current.Add(name, reader.GetString());
                        break;

                    case JsonTokenType.True:
                        current.Add(name, true);
                        break;

                    case JsonTokenType.False:
                        current.Add(name, false);
                        break;

                    case JsonTokenType.Null:
                        current.Add(name);
                        break;

                    case JsonTokenType.Number:
                        if (reader.TryGetInt64(out long longValue))
                        {
                            current.Add(name, longValue);
                        }
                        else
                        {
                            if (reader.TryGetDouble(out double doubleValue))
                            {
                                current.Add(name, doubleValue);
                            }
                            else
                            {
                                throw new FormatException($"NotSupportedNumberValue {Encoding.UTF8.GetBytes(name)}");
                            }
                        }
                        break;

                    default:
                        throw new FormatException("MalformedJson");
                    }
                }
            }

            if (!(reader.TokenType is JsonTokenType.EndObject))
            {
                throw new FormatException("MalformedJson");
            }

            return(header);
        }
Пример #16
0
 public override Jwk WrapKey(Jwk?staticKey, JwtObject header, Span <byte> destination)
 => throw new NotImplementedException();
Пример #17
0
 public EncryptedStatedDescriptor(JwtObject header, StateDescriptor payload)
     : base(header, payload)
 {
 }
Пример #18
0
        private static void AssertDictionaryEqual(Dictionary <string, object> expected, JwtObject value)
        {
            foreach (var expectedItem in expected)
            {
                if (!value.ContainsKey(Encoding.UTF8.GetBytes(expectedItem.Key)))
                {
                    throw new Xunit.Sdk.AssertActualExpectedException(expected, value, $"Expected the key {expectedItem.Key}.");
                }

                var valueItem = value[Encoding.UTF8.GetBytes(expectedItem.Key).AsSpan()];
                if (expectedItem.Value is Dictionary <string, object> expectedDict)
                {
                    if (!(valueItem.Value is JwtObject valueDict))
                    {
                        throw new Xunit.Sdk.AssertActualExpectedException(expected, value, $"Expected the type '{typeof(Dictionary<string, object>)}', got {valueItem.Value?.GetType()}.");
                    }

                    AssertDictionaryEqual(expectedDict, valueDict);
                }
                else if (expectedItem.Value is List <object> expectedList)
                {
                    //#if NETCOREAPP3_0
                    if (!(valueItem.Value is JwtArray valueList))
                    {
                        throw new Xunit.Sdk.AssertActualExpectedException(expected, value, $"Expected the type '{typeof(List<object>)}', got {valueItem.Value?.GetType()}.");
                    }

                    AssertListEqual(expectedList, valueList);
                    //#else
                    //                    if (!(valueItem is JArray valueList))
                    //                    {
                    //                        throw new Xunit.Sdk.AssertActualExpectedException(expected, value, $"Expected the type '{typeof(List<object>)}', got {valueItem?.GetType()}.");
                    //                    }

                    //#endif
                }
                else
                {
                    Assert.Equal(expectedItem.Value, valueItem.Value);
                }
            }
        }