Exemplo n.º 1
0
        /// <summary>DecodeRedirect</summary>
        /// <param name="queryString">string</param>
        /// <returns>デコードされたsaml</returns>
        public static string DecodeRedirect(string queryString)
        {
            // EcodeRedirectの逆
            // --------------------------------------------------
            // Saml → URLデコード → Base64デコード
            //   → DEFLATE解凍 → XML宣言のエンコーディング → XML
            // --------------------------------------------------
            // Samlの抽出
            string saml = "";

            if (queryString.IndexOf("SAMLRequest") != -1)
            {
                saml = StringExtractor.GetParameterFromQueryString("SAMLRequest", queryString);
            }
            else if (queryString.IndexOf("SAMLResponse") != -1)
            {
                saml = StringExtractor.GetParameterFromQueryString("SAMLResponse", queryString);
            }
            else
            {
                return("");
            }

            byte[] tempByte = DeflateCompression.Decompress(
                CustomEncode.FromBase64String(CustomEncode.UrlDecode(saml)));

            //// XML宣言部分を取得するために、us_asciiでデコード
            //string tempString = CustomEncode.ByteToString(tempByte, CustomEncode.us_ascii);

            //// エンコーディング オブジェクトの取得
            //Encoding enc = XmlLib.GetEncodingFromXmlDeclaration(tempString);

            return(CustomEncode.ByteToString(tempByte, CustomEncode.us_ascii)); // enc.CodePage);
        }
Exemplo n.º 2
0
        /// <summary>GetBytesFromPemString</summary>
        /// <param name="pemString">string</param>
        /// <param name="label">string</param>
        /// <returns>Byte[]</returns>
        public static Byte[] GetBytesFromPemString(string pemString, string label)
        {
            string header = String.Format("-----BEGIN {0}-----", label);
            string footer = String.Format("-----END {0}-----", label);

            if (string.IsNullOrEmpty(header))
            {
                return(null);
            }
            if (string.IsNullOrEmpty(footer))
            {
                return(null);
            }

            int start = pemString.IndexOf(header, StringComparison.Ordinal);

            if (start < 0)
            {
                return(null);
            }

            start += header.Length;
            int end = pemString.IndexOf(footer, start, StringComparison.Ordinal) - start;

            if (end < 0)
            {
                return(null);
            }

            // X509Certificate2
            return(CustomEncode.FromBase64String(pemString.Substring(start, end)));
        }
Exemplo n.º 3
0
        /// <summary>VerifyRedirect</summary>
        /// <param name="queryString">string</param>
        /// <param name="dsRSAwithSHA1">DigitalSign</param>
        /// <returns>bool</returns>
        public static bool VerifyRedirect(string queryString, DigitalSign dsRSAwithSHA1)
        {
            // EcodeRedirectの逆

            // Signatureの抽出
            string signature = StringExtractor.GetParameterFromQueryString("Signature", queryString);

            // Signatureの削除
            queryString = queryString.Replace("&Signature=" + signature, "");

            // queryString : ASCIIデコード
            // signature   : パラメタ → URLデコード →  Base64デコード
            if (dsRSAwithSHA1.Verify(
                    CustomEncode.StringToByte(queryString, CustomEncode.us_ascii),
                    CustomEncode.FromBase64String(CustomEncode.UrlDecode(signature))))
            {
                // 署名検証 OK
                return(true);
            }
            else
            {
                // 署名検証 NG
                return(false);
            }
        }
Exemplo n.º 4
0
 /// <summary>MAC値を検証</summary>
 /// <param name="msg">メッセージ(文字列)</param>
 /// <param name="ekha">MACアルゴリズム列挙型</param>
 /// <param name="key">キー(文字列)</param>
 /// <param name="mac">MAC値(base64文字列)</param>
 /// <returns>検証結果( true:検証成功, false:検証失敗 )</returns>
 public static bool VerifyMAC(string msg, EnumKeyedHashAlgorithm ekha, string key, string mac)
 {
     return(MsgAuthCode.VerifyMAC(
                CustomEncode.StringToByte(msg, CustomEncode.UTF_8),
                ekha, CustomEncode.StringToByte(key, CustomEncode.UTF_8),
                CustomEncode.FromBase64String(mac)));
 }
Exemplo n.º 5
0
        /// <summary>検証</summary>
        private void btnDSVerify_Click(object sender, EventArgs e)
        {
            DigitalSignXML   dsXML   = null;
            DigitalSignParam dsParam = null;
            DigitalSignX509  dsX509  = null;

            byte[] data = CustomEncode.StringToByte(this.txtDSData.Text, CustomEncode.UTF_8);
            byte[] sign = CustomEncode.FromBase64String(this.txtDSSign.Text);
            bool   ret  = false;

            if (rbnDSXML.Checked)
            {
                // XMLKey
                dsXML = new DigitalSignXML(
                    (EnumDigitalSignAlgorithm)this.cbxDSPV.SelectedValue, this.txtDSPublicKey.Text);
                ret = dsXML.Verify(data, sign);
            }
            else if (rbnDSParam.Checked)
            {
                // XMLKey
                dsXML = new DigitalSignXML(
                    (EnumDigitalSignAlgorithm)this.cbxDSPV.SelectedValue, this.txtDSPublicKey.Text);

                if (((EnumDigitalSignAlgorithm)this.cbxDSPV.SelectedValue) ==
                    EnumDigitalSignAlgorithm.DSACryptoServiceProvider_SHA1)
                {
                    DSAParameters dsaparam = ((DSACryptoServiceProvider)dsXML.AsymmetricAlgorithm).ExportParameters(false);
                    dsParam = new DigitalSignParam(dsaparam, dsXML.HashAlgorithm);
                }
                else
                {
                    RSAParameters rsaparam = ((RSACryptoServiceProvider)dsXML.AsymmetricAlgorithm).ExportParameters(false);
                    dsParam = new DigitalSignParam(rsaparam, dsXML.HashAlgorithm);
                }

                ret = dsXML.Verify(data, sign);
            }
            else
            {
                // X509
                //// *.pfxを使用して、検証することもできるが、
                //dsX509 = new DigitalSignX509(this.CertificateFilePath_pfx, this.CertificateFilePassword, this.txtCCHash.Text,
                //    X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
                // 通常は、*.cerを使用して検証する。
                dsX509 = new DigitalSignX509(CertificateFilePath_cer, "", this.txtDSHash.Text);

                ret = dsX509.Verify(data, sign);
            }

            if (ret)
            {
                MessageBox.Show("検証成功");
            }
            else
            {
                MessageBox.Show("検証失敗");
            }
        }
        /// <summary>暗号化された文字列を復号化する</summary>
        /// <param name="sourceString">暗号化された文字列</param>
        /// <param name="privateXmlKey">復号化に使用する秘密鍵</param>
        /// <param name="padding">RSAEncryptionPadding</param>
        /// <returns>非対称アルゴリズムで復号化された文字列</returns>
        public string DecryptString(string sourceString, string privateXmlKey = "", RSAEncryptionPadding padding = null)
        {
            // 暗号化文字列をbyte型配列に変換する(Base64)
            byte[] source = CustomEncode.FromBase64String(sourceString);

            // 復号化(UTF-8 Enc)
            return(CustomEncode.ByteToString(
                       this.DecryptBytes(source, privateXmlKey, padding), CustomEncode.UTF_8));
        }
        /// <summary>暗号化された文字列を復号化する</summary>
        /// <param name="sourceString">暗号化された文字列</param>
        /// <param name="privateXmlKey">復号化に使用する秘密鍵</param>
        /// <param name="fOAEP">
        /// ・true  : OAEPパディング(XP以降)
        /// ・false : PKCS#1 v1.5パディング
        /// </param>
        /// <returns>非対称アルゴリズムで復号化された文字列</returns>
        public string DecryptString(string sourceString, string privateXmlKey = "", bool fOAEP = false)
        {
            // 暗号化文字列をbyte型配列に変換する(Base64)
            byte[] source = CustomEncode.FromBase64String(sourceString);

            // 復号化(UTF-8 Enc)
            return(CustomEncode.ByteToString(
                       this.DecryptBytes(source, privateXmlKey, fOAEP), CustomEncode.UTF_8));
        }
Exemplo n.º 8
0
 /// <summary>
 ///  Converts base64 string to deserialized byte array.
 /// </summary>
 /// <param name="base64String">Base64 String</param>
 /// <returns>byte array</returns>
 private byte[] DeserializeFromBase64String(string base64String)
 {
     byte[] deserializeData = null;
     if (string.IsNullOrEmpty(base64String))
     {
         deserializeData = CustomEncode.FromBase64String(base64String);
     }
     return(deserializeData);
 }
Exemplo n.º 9
0
        /// <summary>暗号化された文字列を復号化する</summary>
        /// <param name="sourceString">暗号化された文字列</param>
        /// <param name="password">暗号化に使用したパスワード</param>
        /// <returns>復号化された文字列</returns>
        public string DecryptString(
            string sourceString, string password)
        {
            // 暗号化文字列をbyte型配列に変換する(Base64)
            byte[] source = CustomEncode.FromBase64String(sourceString);

            // 復号化(UTF-8 Enc)
            return(CustomEncode.ByteToString(this.DecryptBytes(source, password), CustomEncode.UTF_8));
        }
Exemplo n.º 10
0
        /// <summary>暗号化された文字列を復号化する</summary>
        /// <param name="sourceString">暗号化された文字列</param>
        /// <param name="privateKey">復号化に使用する秘密鍵</param>
        /// <returns>非対称アルゴリズムで復号化された文字列</returns>
        public static string DecryptString(string sourceString, string privateKey)
        {
            // 暗号化文字列をbyte型配列に変換する(Base64)
            byte[] source = CustomEncode.FromBase64String(sourceString);

            // 復号化(UTF-8 Enc)
            return(CustomEncode.ByteToString(
                       ASymmetricCryptography.DecryptBytes(source, privateKey), CustomEncode.UTF_8));
        }
Exemplo n.º 11
0
        /// <summary>暗号化された文字列を復号化する</summary>
        /// <param name="sourceString">暗号化された文字列</param>
        /// <param name="password">暗号化に使用したパスワード</param>
        /// <param name="esa">
        /// 対称アルゴリズムによる
        /// 暗号化サービスプロバイダの種類
        /// </param>
        /// <param name="salt">ソルト</param>
        /// <param name="stretching">ストレッチング</param>
        /// <returns>
        /// 対称アルゴリズムで
        /// 復号化された文字列
        /// </returns>
        public static string DecryptString(
            string sourceString, string password, EnumSymmetricAlgorithm esa, byte[] salt, int stretching)
        {
            // 暗号化文字列をbyte型配列に変換する(Base64)
            byte[] source = CustomEncode.FromBase64String(sourceString);

            // 復号化(UTF-8 Enc)
            return(CustomEncode.ByteToString(
                       SymmetricCryptography.DecryptBytes(source, password, esa, salt, stretching), CustomEncode.UTF_8));
        }
Exemplo n.º 12
0
        /// <summary>Main</summary>
        /// <param name="args">string[]</param>
        static void Main(string[] args)
        {
            string ver = "";

#if NET45
            ver = "NET45";
#elif NET46
            ver = "NET46";
#elif NET47
            ver = "NET47";
#elif NET48
            ver = "NET48";
#elif NETCORE20
            ver = "NETCORE20";
#elif NETCORE30
            ver = "NETCORE30";
#else
#endif

            string filePath = "";
            string fileName = "TestBinarySerializeXplat.txt";
            if (System.Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                filePath = @"C:\Users\nishi\";
            }
            else
            {
                filePath = "/mnt/c/Users/nishi/";
            }

            filePath += fileName;

            Dictionary <string, string> dic = null;
            if (File.Exists(filePath))
            {
                dic = (Dictionary <string, string>)
                      BinarySerialize.BytesToObject(
                    CustomEncode.FromBase64String(
                        ResourceLoader.LoadAsString(filePath, Encoding.UTF8)));

                Console.WriteLine("loaded string : " + dic["ver"]);
                Console.ReadKey();
            }

            dic        = new Dictionary <string, string>();
            dic["ver"] = ver;

            using (StreamWriter sr = new System.IO.StreamWriter(filePath, false, Encoding.UTF8))
            {
                sr.WriteLine(
                    CustomEncode.ToBase64String(
                        BinarySerialize.ObjectToBytes(dic)));
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Converts string data to byte array and byte array data to object.
        /// </summary>
        /// <param name="strBase64">Base64 String</param>
        /// <returns>Deserialized Object</returns>
        public object DeserializeFromBase64(string strBase64)
        {
            byte[]          deserializeData = null;
            MemoryStream    memStream       = new MemoryStream();
            BinaryFormatter binForm         = new BinaryFormatter();

            deserializeData = CustomEncode.FromBase64String(strBase64);
            memStream.Write(deserializeData, 0, deserializeData.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            object obj = (object)binForm.Deserialize(memStream);

            return(obj);
        }
Exemplo n.º 14
0
        public static void ToBase64StringTest(byte[] aryByt)
        {
            string base64Decoded;

            //convert to byte using components of Touryo
            base64Decoded = CustomEncode.ToBase64String(aryByt);

            //convert to string using components of Touryo
            byte[] data = CustomEncode.FromBase64String(base64Decoded);

            //check whether it is converted to original byte
            Assert.AreEqual(aryByt, data);
        }
Exemplo n.º 15
0
        public static void FromBase64StringTest(string base64Str)
        {
            string base64Decoded;

            //convert to byte using components of Touryo
            byte[] data = CustomEncode.FromBase64String(base64Str);

            //convert to string unsing components of Touryo
            base64Decoded = CustomEncode.ToBase64String(data);

            //check whether the two strings are equal.
            Assert.AreEqual(base64Str, base64Decoded);
        }
Exemplo n.º 16
0
        /// <summary>DecodePost</summary>
        /// <param name="saml">エンコードされたsaml</param>
        /// <returns>デコードされたsaml</returns>
        public static string DecodePost(string saml)
        {
            // EncodePostの逆

            // Base64エンコード → XML宣言のエンコーディング → XML
            byte[] tempByte = CustomEncode.FromBase64String(saml);

            //// XML宣言部分を取得するために、us_asciiでデコード
            //string tempString = CustomEncode.ByteToString(tempByte, CustomEncode.us_ascii);

            //// エンコーディング オブジェクトの取得
            //Encoding enc = XmlLib.GetEncodingFromXmlDeclaration(tempString);

            return(CustomEncode.ByteToString(tempByte, CustomEncode.us_ascii)); // enc.CodePage);
        }
Exemplo n.º 17
0
 public string[] ValidateAuthTicket(string authTicket)
 {
     try
     {
         // 認証チケットの復号化
         return((string[])BinarySerialize.BytesToObject(
                    CustomEncode.FromBase64String(
                        SymmetricCryptography.DecryptString(
                            authTicket, GetConfigParameter.GetConfigValue("private-key"),
                            EnumSymmetricAlgorithm.TripleDESCryptoServiceProvider))));
     }
     catch
     {
         // 認証失敗
         return(null);
     }
 }
Exemplo n.º 18
0
        /// <summary>パスワードを比較して認証する。</summary>
        /// <param name="rawPassword">Password entered by the user.</param>
        /// <param name="saltedPassword">Salted and hashed password.</param>
        /// <param name="eha">ハッシュ・アルゴリズム列挙型</param>
        /// <returns>
        /// true:パスワードは一致した。
        /// false:パスワードは一致しない。
        /// </returns>
        public static bool EqualSaltedPassword(string rawPassword, string saltedPassword, EnumHashAlgorithm eha)
        {
            // ソルト部分を取得
            string[] temp           = saltedPassword.Split('.');
            string   salt           = CustomEncode.ByteToString(CustomEncode.FromBase64String(temp[0]), CustomEncode.UTF_8);
            int      stretchCount   = int.Parse(CustomEncode.ByteToString(CustomEncode.FromBase64String(temp[1]), CustomEncode.UTF_8));
            string   hashedPassword = CustomEncode.ByteToString(CustomEncode.FromBase64String(temp[2]), CustomEncode.UTF_8);

            // 引数のsaltedPasswordと、rawPasswordから自作したsaltedPasswordを比較
            if (hashedPassword == GetHash.GetHashString(salt + rawPassword, eha, stretchCount))
            {
                // 一致した。
                return(true);
            }
            else
            {
                // 一致しなかった。
                return(false);
            }
        }
Exemplo n.º 19
0
        /// <summary>パスワードを比較して認証する。</summary>
        /// <param name="rawPassword">Password entered by the user.</param>
        /// <param name="saltedPassword">Salted and hashed password.</param>
        /// <param name="ekha">ハッシュ・アルゴリズム列挙型</param>
        /// <returns>
        /// true:パスワードは一致した。
        /// false:パスワードは一致しない。
        /// </returns>
        public static bool EqualSaltedPassword(string rawPassword, string saltedPassword, EnumKeyedHashAlgorithm ekha)
        {
            // ソルト部分を取得
            string[] temp = saltedPassword.Split('.');

            // key
            string key = CustomEncode.ByteToString(CustomEncode.FromBase64String(temp[0]), CustomEncode.UTF_8);

            // saltByte
            byte[] saltByte = CustomEncode.FromBase64String(temp[1]);

            // salt
            string salt = CustomEncode.ByteToString(saltByte, CustomEncode.UTF_8);

            // stretchCount
            int stretchCount = int.Parse(CustomEncode.ByteToString(CustomEncode.FromBase64String(temp[2]), CustomEncode.UTF_8));

            // Salted and hashed password
            string hashedPassword = temp[3];

            // KeyedHashのキーを生成する。
            Rfc2898DeriveBytes passwordKey = new Rfc2898DeriveBytes(key, saltByte, stretchCount);

            // 引数のsaltedPasswordと、rawPasswordから自作したsaltedPasswordを比較
            string compare = CustomEncode.ToBase64String(
                GetPasswordHashV2.GetKeyedHashBytes(
                    CustomEncode.StringToByte(salt + rawPassword, CustomEncode.UTF_8),
                    ekha, passwordKey.GetBytes(24)));

            if (hashedPassword == compare)
            {
                // 一致した。
                return(true);
            }
            else
            {
                // 一致しなかった。
                return(false);
            }
        }
        public async Task <ActionResult> TestJWTBearerTokenFlow()
        {
            // Token2エンドポイントにアクセス
            string aud = ASPNETIdentityConfig.OAuth2AuthorizationServerEndpointsRootURI
                         + ASPNETIdentityConfig.OAuth2BearerTokenEndpoint2;

            // ClientNameから、client_id(iss)を取得。
            string iss = "";

            if (User.Identity.IsAuthenticated)
            {
                // User Accountの場合、
                iss = OAuth2Helper.GetInstance().GetClientIdByName(User.Identity.Name);
            }
            else
            {
                // Client Accountの場合、
                iss = OAuth2Helper.GetInstance().GetClientIdByName("TestClient");
            }

            // テストなので秘密鍵は共通とする。
            string privateKey = OAuth2AndOIDCParams.OAuth2JwtAssertionPrivatekey;

            privateKey = CustomEncode.ByteToString(CustomEncode.FromBase64String(privateKey), CustomEncode.us_ascii);

            string response = await OAuth2Helper.GetInstance()
                              .JwtBearerTokenFlowAsync(new Uri(
                                                           ASPNETIdentityConfig.OAuth2AuthorizationServerEndpointsRootURI
                                                           + ASPNETIdentityConfig.OAuth2BearerTokenEndpoint2),
                                                       JwtAssertion.CreateJwtBearerTokenFlowAssertion(
                                                           iss, aud, new TimeSpan(0, 0, 30), ASPNETIdentityConst.StandardScopes, privateKey));

            ViewBag.Response    = response;
            ViewBag.AccessToken = ((JObject)JsonConvert.DeserializeObject(response))[OAuth2AndOIDCConst.AccessToken];

            return(View("OAuth2ClientAuthenticationFlow"));
        }
Exemplo n.º 21
0
        /// <summary>GetCredentials</summary>
        /// <param name="authHeader">string</param>
        /// <param name="credentials">string[]</param>
        /// <returns>AuthenticationScheme</returns>
        public static string GetCredentials(string authHeader, out string[] credentials)
        {
            if (!string.IsNullOrEmpty(authHeader))
            {
                string[] temp = authHeader.Split(' ');

                if (temp[0] == OAuth2AndOIDCConst.Basic)
                {
                    credentials = CustomEncode.ByteToString(
                        CustomEncode.FromBase64String(temp[1]), CustomEncode.us_ascii).Split(':');

                    return(OAuth2AndOIDCConst.Basic);
                }
                else if (temp[0] == OAuth2AndOIDCConst.Bearer)
                {
                    credentials = new string[] { temp[1] };

                    return(OAuth2AndOIDCConst.Bearer);
                }
            }

            credentials = new string[] { };
            return("");
        }
Exemplo n.º 22
0
        /// <summary>検証</summary>
        private void btnCCVerify_Click(object sender, EventArgs e)
        {
            DigitalSignXML  csXML  = null;
            DigitalSignX509 csX509 = null;

            byte[] data = CustomEncode.StringToByte(this.txtCCData.Text, CustomEncode.UTF_8);
            byte[] sign = CustomEncode.FromBase64String(this.txtCCSign.Text);
            bool   ret  = false;

            if (rbnCCXML.Checked)
            {
                // XMLKey
                csXML = new DigitalSignXML((EnumDigitalSignAlgorithm)this.cbxCCXMLPV.SelectedValue);
                csXML.XMLPublicKey = txtCCPublicKey.Text;
                ret = csXML.Verify(data, sign);
            }
            else
            {
                // X509Cer
                // *.pfxを使用して、検証することもできるが、
                //csX509 = new CodeSigningX509(this.CertificateFilePath_pfx, this.CertificateFilePassword, this.txtCCHash.Text);
                // 通常は、*.cerを使用して検証する。
                csX509 = new DigitalSignX509(CertificateFilePath_cer, "", this.txtCCHash.Text);

                ret = csX509.Verify(data, sign);
            }

            if (ret)
            {
                MessageBox.Show("検証成功");
            }
            else
            {
                MessageBox.Show("検証失敗");
            }
        }
Exemplo n.º 23
0
        //[Authorize]
        public Dictionary <string, string> OAuth2BearerToken2(FormDataCollection formData)
        {
            // 戻り値
            // ・正常
            Dictionary <string, string> ret = new Dictionary <string, string>();
            // ・異常
            Dictionary <string, string> err = new Dictionary <string, string>();

            // 変数
            string grant_type = formData[OAuth2AndOIDCConst.grant_type];
            string assertion  = formData[OAuth2AndOIDCConst.assertion];

            // クライアント認証
            if (grant_type == OAuth2AndOIDCConst.JwtBearerTokenFlowGrantType)
            {
                Dictionary <string, string> dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(
                    CustomEncode.ByteToString(CustomEncode.FromBase64UrlString(
                                                  assertion.Split('.')[1]), CustomEncode.us_ascii));

                string pubKey = OAuth2Helper.GetInstance().GetJwtAssertionPublickey(dic[OAuth2AndOIDCConst.iss]);
                pubKey = CustomEncode.ByteToString(CustomEncode.FromBase64String(pubKey), CustomEncode.us_ascii);

                if (!string.IsNullOrEmpty(pubKey))
                {
                    string  iss    = "";
                    string  aud    = "";
                    string  scopes = "";
                    JObject jobj   = null;

                    if (JwtAssertion.VerifyJwtBearerTokenFlowAssertion(assertion, out iss, out aud, out scopes, out jobj, pubKey))
                    {
                        // aud 検証
                        if (aud == ASPNETIdentityConfig.OAuth2AuthorizationServerEndpointsRootURI
                            + ASPNETIdentityConfig.OAuth2BearerTokenEndpoint2)
                        {
                            // ここからは、JwtAssertionではなく、JwtTokenを作るので、属性設定に注意。
                            ClaimsIdentity identity = OAuth2Helper.AddClaim(
                                new ClaimsIdentity(OAuthDefaults.AuthenticationType), iss, "", scopes.Split(' '), "");

                            AuthenticationProperties prop = new AuthenticationProperties();
                            prop.IssuedUtc  = DateTimeOffset.UtcNow;
                            prop.ExpiresUtc = DateTimeOffset.Now.Add(ASPNETIdentityConfig.OAuth2AccessTokenExpireTimeSpanFromMinutes);

                            // token_type
                            ret.Add(OAuth2AndOIDCConst.token_type, OAuth2AndOIDCConst.Bearer.ToLower());

                            // access_token
                            AccessTokenFormatJwt verifier = new AccessTokenFormatJwt();
                            string access_token           = verifier.Protect(new AuthenticationTicket(identity, prop));
                            ret.Add(OAuth2AndOIDCConst.AccessToken, access_token);

                            // expires_in
                            jobj = (JObject)JsonConvert.DeserializeObject(
                                CustomEncode.ByteToString(CustomEncode.FromBase64UrlString(
                                                              access_token.Split('.')[1]), CustomEncode.us_ascii));
                            ret.Add("expires_in", (long.Parse((string)jobj[OAuth2AndOIDCConst.exp]) - long.Parse((string)jobj[OAuth2AndOIDCConst.iat])).ToString());

                            // オペレーション・トレース・ログ出力
                            string clientName = OAuth2Helper.GetInstance().GetClientName(iss);
                            Logging.MyOperationTrace(string.Format(
                                                         "{0}({1}) passed the 'jwt bearer token flow' by {2}({3}).",
                                                         iss, clientName, iss, clientName));

                            return(ret); // 成功
                        }
                        else
                        {
                            // クライアント認証エラー(Credential(aud)不正
                            err.Add("error", "invalid_client");
                            err.Add("error_description", "Invalid credential");
                        }
                    }
                    else
                    {
                        // クライアント認証エラー(Credential(署名)不正
                        err.Add("error", "invalid_client");
                        err.Add("error_description", "Invalid credential");
                    }
                }
                else
                {
                    // クライアント認証エラー(Credential(iss or pubKey)不正
                    err.Add("error", "invalid_client");
                    err.Add("error_description", "Invalid credential");
                }
            }
            else
            {
                // grant_type パラメタ・エラー
                err.Add("error", "invalid_request");
                err.Add("error_description", "invalid grant_type");
            }

            return(err); // 失敗
        }
Exemplo n.º 24
0
        //[Authorize]
        public Dictionary <string, string> IntrospectToken(FormDataCollection formData)
        {
            // 戻り値
            // ・正常
            Dictionary <string, string> ret = new Dictionary <string, string>();
            // ・異常
            Dictionary <string, string> err = new Dictionary <string, string>();

            // 変数
            string[] temp            = null;
            string   token           = formData[OAuth2AndOIDCConst.token];
            string   token_type_hint = formData[OAuth2AndOIDCConst.token_type_hint];

            // クライアント認証

            // クライアント識別子
            string authHeader = HttpContext.Current.Request.Headers[OAuth2AndOIDCConst.HttpHeader_Authorization];

            temp = authHeader.Split(' ');

            if (temp[0] == OAuth2AndOIDCConst.Basic)
            {
                temp = CustomEncode.ByteToString(
                    CustomEncode.FromBase64String(temp[1]), CustomEncode.us_ascii).Split(':');

                string clientId     = temp[0];
                string clientSecret = temp[1];

                if (!(string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(clientSecret)))
                {
                    // *.config or OAuth2Dataテーブルを参照してクライアント認証を行なう。
                    if (clientSecret == OAuth2Helper.GetInstance().GetClientSecret(clientId))
                    {
                        // 検証完了
                        AuthenticationTicket ticket = null;

                        if (token_type_hint == OAuth2AndOIDCConst.AccessToken)
                        {
                            // 検証
                            AccessTokenFormatJwt verifier = new AccessTokenFormatJwt();
                            ticket = verifier.Unprotect(token);

                            if (ticket == null)
                            {
                                // 検証失敗
                                // 検証エラー
                                err.Add("error", "invalid_request");
                                err.Add("error_description", "invalid token");
                            }
                            else
                            {
                                // 検証成功
                                // メタデータの返却
                                ret.Add("active", "true");
                                ret.Add(OAuth2AndOIDCConst.token_type, token_type_hint);

                                string scopes = "";
                                foreach (Claim claim in ticket.Identity.Claims)
                                {
                                    if (claim.Type.StartsWith(OAuth2AndOIDCConst.Claim_Base))
                                    {
                                        if (claim.Type == OAuth2AndOIDCConst.Claim_Scopes)
                                        {
                                            scopes += claim.Value + " ";
                                        }
                                        else
                                        {
                                            ret.Add(claim.Type.Substring(
                                                        OAuth2AndOIDCConst.Claim_Base.Length), claim.Value);
                                        }
                                    }
                                }
                                ret.Add(OAuth2AndOIDCConst.Claim_Scopes.Substring(
                                            OAuth2AndOIDCConst.Claim_Base.Length), scopes.Trim());

                                return(ret); // 成功
                            }
                        }
                        else if (token_type_hint == OAuth2AndOIDCConst.RefreshToken)
                        {
                            // refresh_token参照
                            ticket = RefreshTokenProvider.ReferDirectly(token);

                            if (ticket == null)
                            {
                                // 検証失敗
                                // 検証エラー
                                err.Add("error", "invalid_request");
                                err.Add("error_description", "invalid token");
                            }
                            else
                            {
                                // 検証成功
                                // メタデータの返却
                                ret.Add("active", "true");
                                ret.Add(OAuth2AndOIDCConst.token_type, token_type_hint);

                                string scopes = "";
                                foreach (Claim claim in ticket.Identity.Claims)
                                {
                                    if (claim.Type.StartsWith(OAuth2AndOIDCConst.Claim_Base))
                                    {
                                        if (claim.Type == OAuth2AndOIDCConst.Claim_Scopes)
                                        {
                                            scopes += claim.Value + " ";
                                        }
                                        else
                                        {
                                            ret.Add(claim.Type.Substring(
                                                        OAuth2AndOIDCConst.Claim_Base.Length), claim.Value);
                                        }
                                    }
                                }
                                ret.Add(OAuth2AndOIDCConst.Claim_Scopes.Substring(
                                            OAuth2AndOIDCConst.Claim_Base.Length), scopes.Trim());

                                return(ret); // 成功
                            }
                        }
                        else
                        {
                            // token_type_hint パラメタ・エラー
                            err.Add("error", "invalid_request");
                            err.Add("error_description", "invalid token_type_hint");
                        }
                    }
                    else
                    {
                        // クライアント認証エラー(Credential不正
                        err.Add("error", "invalid_client");
                        err.Add("error_description", "Invalid credential");
                    }
                }
                else
                {
                    // クライアント認証エラー(Credential不正
                    err.Add("error", "invalid_client");
                    err.Add("error_description", "Invalid credential");
                }
            }
            else
            {
                // クライアント認証エラー(ヘッダ不正
                err.Add("error", "invalid_request");
                err.Add("error_description", "Invalid authentication header");
            }

            return(err); // 失敗
        }
Exemplo n.º 25
0
        //[Authorize]
        public Dictionary <string, string> RevokeToken(FormDataCollection formData)
        {
            // 戻り値(エラー)
            Dictionary <string, string> err = new Dictionary <string, string>();

            // 変数
            string[] temp            = null;
            string   token           = formData[OAuth2AndOIDCConst.token];
            string   token_type_hint = formData[OAuth2AndOIDCConst.token_type_hint];

            // クライアント認証

            // クライアント識別子
            string authHeader = HttpContext.Current.Request.Headers[OAuth2AndOIDCConst.HttpHeader_Authorization];

            temp = authHeader.Split(' ');

            if (temp[0] == OAuth2AndOIDCConst.Basic)
            {
                temp = CustomEncode.ByteToString(
                    CustomEncode.FromBase64String(temp[1]), CustomEncode.us_ascii).Split(':');

                string clientId     = temp[0];
                string clientSecret = temp[1];

                if (!(string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(clientSecret)))
                {
                    // *.config or OAuth2Dataテーブルを参照してクライアント認証を行なう。
                    if (clientSecret == OAuth2Helper.GetInstance().GetClientSecret(clientId))
                    {
                        // 検証完了

                        if (token_type_hint == OAuth2AndOIDCConst.AccessToken)
                        {
                            // 検証
                            AccessTokenFormatJwt verifier = new AccessTokenFormatJwt();
                            AuthenticationTicket ticket   = verifier.Unprotect(token);

                            if (ticket == null)
                            {
                                // 検証失敗
                                // 検証エラー
                                err.Add("error", "invalid_request");
                                err.Add("error_description", "invalid token");
                            }
                            else
                            {
                                // 検証成功

                                // jtiの取り出し
                                Claim jti = ticket.Identity.Claims.Where(
                                    x => x.Type == OAuth2AndOIDCConst.Claim_JwtId).FirstOrDefault <Claim>();

                                // access_token取消
                                OAuth2RevocationProvider.GetInstance().Create(jti.Value);
                                return(null); // 成功
                            }
                        }
                        else if (token_type_hint == OAuth2AndOIDCConst.RefreshToken)
                        {
                            // refresh_token取消
                            if (RefreshTokenProvider.DeleteDirectly(token))
                            {
                                // 取り消し成功
                                return(null); // 成功
                            }
                            else
                            {
                                // 取り消し失敗
                                err.Add("error", "invalid_request");
                                err.Add("error_description", "invalid token");
                            }
                        }
                        else
                        {
                            // token_type_hint パラメタ・エラー
                            err.Add("error", "invalid_request");
                            err.Add("error_description", "invalid token_type_hint");
                        }
                    }
                    else
                    {
                        // クライアント認証エラー(Credential不正
                        err.Add("error", "invalid_client");
                        err.Add("error_description", "Invalid credential");
                    }
                }
                else
                {
                    // クライアント認証エラー(Credential不正
                    err.Add("error", "invalid_client");
                    err.Add("error_description", "Invalid credential");
                }
            }
            else
            {
                // クライアント認証エラー(ヘッダ不正
                err.Add("error", "invalid_request");
                err.Add("error_description", "Invalid authentication header");
            }

            return(err); // 失敗
        }
Exemplo n.º 26
0
        /// <summary>
        /// Authorization Code、Resource Owner Password Credentialsl、Client Credentialsグラント種別において、
        /// OAuthBearerTokenEndpointPathを処理する場合に発生する、" クライアント認証 " を行なうメソッド。
        /// " クライアント認証 "では、以下の両方の要素を検証する。
        /// ・context.ClientId が、登録された "client_id" であること。
        /// ・その他、資格情報が要求に存在していることを検証する。
        /// </summary>
        /// <param name="context">OAuthValidateClientAuthenticationContext</param>
        /// <returns>Task</returns>
        /// <see cref="https://msdn.microsoft.com/ja-jp/library/dn385497.aspx"/>
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // クライアント識別子
            string clientId     = "";
            string clientSecret = "";

            // ・context.Validated を呼び出し、contextを検証完了に設定する。
            // ・検証完了にしなければ要求はそれ以上先には進まない。
            //context.Validated(clientId);

            #region クライアント認証を行なう。

            if (string.IsNullOrEmpty(context.Parameters[OAuth2AndOIDCConst.grant_type]))
            {
                // 指定なし。
                // 検証未完
            }
            else if (context.Parameters[OAuth2AndOIDCConst.grant_type].ToLower() == OAuth2AndOIDCConst.AuthorizationCodeGrantType)
            {
                #region Authorization Codeグラント種別

                // "client_id" および "client_secret"を基本認証の認証ヘッダから取得
                if (context.TryGetBasicCredentials(out clientId, out clientSecret))
                {
                    // 通常のクライアント認証
                    if (!(string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(clientSecret)))
                    {
                        // *.config or OAuth2Dataテーブルを参照してクライアント認証を行なう。
                        if (clientSecret == OAuth2Helper.GetInstance().GetClientSecret(context.ClientId))
                        {
                            // 検証完了
                            context.Validated(clientId);
                        }
                    }
                }
                else
                {
                    // その他のクライアント認証の可能性
                    string assertion = context.Parameters.Get(OAuth2AndOIDCConst.assertion);
                    if (!string.IsNullOrEmpty(assertion))
                    {
                        // JWT client assertion
                        Dictionary <string, string> dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(
                            CustomEncode.ByteToString(CustomEncode.FromBase64UrlString(
                                                          assertion.Split('.')[1]), CustomEncode.us_ascii));

                        string pubKey = OAuth2Helper.GetInstance().GetJwtAssertionPublickey(dic[OAuth2AndOIDCConst.iss]);
                        pubKey = CustomEncode.ByteToString(CustomEncode.FromBase64String(pubKey), CustomEncode.us_ascii);

                        if (!string.IsNullOrEmpty(pubKey))
                        {
                            string  iss    = "";
                            string  aud    = "";
                            string  scopes = "";
                            JObject jobj   = null;

                            if (JwtAssertion.VerifyJwtBearerTokenFlowAssertion(
                                    assertion, out iss, out aud, out scopes, out jobj, pubKey))
                            {
                                // aud 検証
                                if (aud == ASPNETIdentityConfig.OAuth2AuthorizationServerEndpointsRootURI
                                    + ASPNETIdentityConfig.OAuth2BearerTokenEndpoint)
                                {
                                    // 検証完了
                                    context.Validated(iss);
                                }
                            }
                        }
                    }
                    else
                    {
                        // クライアント認証なしエラー
                    }
                }

                #endregion
            }
            else if (context.Parameters[OAuth2AndOIDCConst.grant_type].ToLower() == OAuth2AndOIDCConst.ResourceOwnerPasswordCredentialsGrantType)
            {
                #region Resource Owner Password Credentialsグラント種別

                #region 参考
                // Simple OAuth Server: Implementing a Simple OAuth Server with Katana
                // OAuth Authorization Server Components (Part 1) - Tugberk Ugurlu's Blog
                // http://www.tugberkugurlu.com/archive/simple-oauth-server-implementing-a-simple-oauth-server-with-katana-oauth-authorization-server-components-part-1
                // ・・・ 基本認証を使用する既存のクライアントを認証してOAuthに移行する。
                #endregion

                // "client_id" および "client_secret"を基本認証の認証ヘッダから取得
                if (context.TryGetBasicCredentials(out clientId, out clientSecret))
                {
                    if (!(string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(clientSecret)))
                    {
                        // *.config or OAuth2Dataテーブルを参照してクライアント認証を行なう。
                        if (clientSecret == OAuth2Helper.GetInstance().GetClientSecret(context.ClientId))
                        {
                            // 検証完了
                            context.Validated(clientId);
                        }
                    }
                }

                #endregion
            }
            else if (context.Parameters[OAuth2AndOIDCConst.grant_type].ToLower() == OAuth2AndOIDCConst.ClientCredentialsGrantType)
            {
                #region Client Credentialsグラント種別

                // "client_id" および "client_secret"を基本認証の認証ヘッダから取得
                if (context.TryGetBasicCredentials(out clientId, out clientSecret))
                {
                    if (!(string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(clientSecret)))
                    {
                        // *.config or OAuth2Dataテーブルを参照してクライアント認証を行なう。
                        if (clientSecret == OAuth2Helper.GetInstance().GetClientSecret(context.ClientId))
                        {
                            // 検証完了
                            context.Validated(clientId);
                        }
                    }
                }

                #endregion
            }
            else if (context.Parameters[OAuth2AndOIDCConst.grant_type].ToLower() == OAuth2AndOIDCConst.RefreshTokenGrantType)
            {
                #region RefreshToken

                if (!ASPNETIdentityConfig.EnableRefreshToken)
                {
                    throw new NotSupportedException(Resources.ApplicationOAuthBearerTokenProvider.EnableRefreshToken);
                }

                // "client_id" および "client_secret"を基本認証の認証ヘッダから取得
                if (context.TryGetBasicCredentials(out clientId, out clientSecret))
                {
                    if (!(string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(clientSecret)))
                    {
                        // *.config or OAuth2Dataテーブルを参照してクライアント認証を行なう。
                        if (clientSecret == OAuth2Helper.GetInstance().GetClientSecret(context.ClientId))
                        {
                            // 検証完了
                            context.Validated(clientId);
                        }
                    }
                }

                #endregion
            }
            else
            {
                // 不明な値
                // 検証未完
            }

            #endregion

            // 結果を返す。
            return(Task.FromResult(0));
        }
Exemplo n.º 27
0
 /// <summary>GetObjectFromBinary拡張メソッド</summary>
 /// <param name="session">ISession</param>
 /// <param name="key">string</param>
 /// <returns>object</returns>
 public static object GetObjectFromBinary(this ISession session, string key)
 {
     return(BinarySerialize.BytesToObject(
                CustomEncode.FromBase64String(
                    session.GetString(key))));
 }
        public async Task <Dictionary <string, string> > DotNETOnlineWebAPI(Dictionary <string, string> paramDic)
        {
            // 引数
            string serviceName = paramDic["ServiceName"];

            byte[] contextObject        = CustomEncode.FromBase64String(paramDic["ContextObject"]);
            byte[] parameterValueObject = CustomEncode.FromBase64String(paramDic["ParameterValueObject"]);

            // 戻り値
            byte[] ret = null;
            byte[] returnValueObject = null;
            Dictionary <string, string> returnDic = new Dictionary <string, string>();

            // ステータス
            string status = "-";

            // 初期化のため
            returnValueObject = null;

            #region 呼出し制御関係の変数

            // アセンブリ名
            string assemblyName = "";

            // クラス名
            string className = "";

            #endregion

            #region 引数・戻り値関係の変数

            // コンテキスト情報
            object context; // 2009/09/29-この行

            // 引数・戻り値の.NETオブジェクト
            BaseParameterValue parameterValue = null;
            BaseReturnValue    returnValue    = null;

            // エラー情報(クライアント側で復元するため)
            WSErrorInfo wsErrorInfo = new WSErrorInfo();

            // エラー情報(ログ出力用)
            string errorType      = ""; // 2009/09/15-この行
            string errorMessageID = "";
            string errorMessage   = "";
            string errorToString  = "";

            #endregion

            try
            {
                // 開始ログの出力
                LogIF.InfoLog("SERVICE-IF", FxLiteral.SIF_STATUS_START);

                #region  前解決

                // ★
                status = FxLiteral.SIF_STATUS_NAME_SERVICE;

                // 名前解決(インプロセス)
                FxController.IPR_NS.NameResolution(serviceName, out assemblyName, out className);

                #endregion

                #region 引数のデシリアライズ

                // ★
                status = FxLiteral.SIF_STATUS_DESERIALIZE;

                // コンテキストクラスの.NETオブジェクト化
                context = BinarySerialize.BytesToObject(contextObject); // 2009/09/29-この行
                // ※ コンテキストの利用方法は任意だが、サービスインターフェイス上での利用に止める。

                // 引数クラスの.NETオブジェクト化
                parameterValue = (BaseParameterValue)BinarySerialize.BytesToObject(parameterValueObject);

                // 引数クラスをパラメタ セットに格納
                object[] paramSet = new object[] { parameterValue, DbEnum.IsolationLevelEnum.User };

                #endregion

                #region 認証処理のUOC

                // ★
                status = FxLiteral.SIF_STATUS_AUTHENTICATION;

                if (context is string)
                {
                    // System.Stringの場合
                    string access_token = (string)context;
                    if (!string.IsNullOrEmpty(access_token))
                    {
                        string        sub    = "";
                        List <string> roles  = null;
                        List <string> scopes = null;
                        JObject       jobj   = null;

                        if (JwtToken.Verify(access_token, out sub, out roles, out scopes, out jobj))
                        {
                            // 認証成功
                            Debug.WriteLine("認証成功");
                        }
                        else
                        {
                            // 認証失敗(認証必須ならエラーにする。
                        }
                    }
                    else
                    {
                        // 認証失敗(認証必須ならエラーにする。
                    }
                }
                else
                {
                    // MyUserInfoの場合
                }

                //contextObject = BinarySerialize.ObjectToBytes(hogehoge); // 更新可能だが...。

                #endregion

                #region B層・D層呼出し

                // ★
                status = FxLiteral.SIF_STATUS_INVOKE;

                // #17-start
                try
                {
                    // B層・D層呼出し
                    Task <BaseReturnValue> result = (Task <BaseReturnValue>)Latebind.InvokeMethod(
                        assemblyName, className,
                        FxLiteral.TRANSMISSION_INPROCESS_ASYNC_METHOD_NAME, paramSet);
                    returnValue = await result;
                }
                catch (System.Reflection.TargetInvocationException rtEx)
                {
                    //// InnerExceptionを投げなおす。
                    //throw rtEx.InnerException;

                    // スタックトレースを保って InnerException を throw
                    ExceptionDispatchInfo.Capture(rtEx.InnerException).Throw();
                }
                // #17-end

                #endregion

                #region 戻り値のシリアライズ

                // ★
                status = FxLiteral.SIF_STATUS_SERIALIZE;

                returnValueObject = BinarySerialize.ObjectToBytes(returnValue);

                #endregion

                // ★
                status = "";

                // 戻り値を返す。
                ret = BinarySerialize.ObjectToBytes("");
            }
            catch (BusinessSystemException bsEx)
            {
                // システム例外

                // エラー情報を設定する。
                wsErrorInfo.ErrorType      = FxEnum.ErrorType.BusinessSystemException;
                wsErrorInfo.ErrorMessageID = bsEx.messageID;
                wsErrorInfo.ErrorMessage   = bsEx.Message;

                // ログ出力用の情報を保存
                errorType      = FxEnum.ErrorType.BusinessSystemException.ToString(); // 2009/09/15-この行
                errorMessageID = bsEx.messageID;
                errorMessage   = bsEx.Message;

                errorToString = bsEx.ToString();

                // エラー情報を戻す。
                ret = BinarySerialize.ObjectToBytes(wsErrorInfo);
            }
            catch (FrameworkException fxEx)
            {
                // フレームワーク例外
                // ★ インナーエクセプション情報は消失

                // エラー情報を設定する。
                wsErrorInfo.ErrorType      = FxEnum.ErrorType.FrameworkException;
                wsErrorInfo.ErrorMessageID = fxEx.messageID;
                wsErrorInfo.ErrorMessage   = fxEx.Message;

                // ログ出力用の情報を保存
                errorType      = FxEnum.ErrorType.FrameworkException.ToString(); // 2009/09/15-この行
                errorMessageID = fxEx.messageID;
                errorMessage   = fxEx.Message;

                errorToString = fxEx.ToString();

                // エラー情報を戻す。
                ret = BinarySerialize.ObjectToBytes(wsErrorInfo);
            }
            catch (Exception ex)
            {
                // ログ出力用の情報を保存
                errorType      = FxEnum.ErrorType.ElseException.ToString(); // 2009/09/15-この行
                errorMessageID = "-";
                errorMessage   = ex.Message;

                errorToString = ex.ToString();

                throw; // SoapExceptionになって伝播
            }
            finally
            {
                //// Sessionステートレス
                //Session.Clear();
                //Session.Abandon();

                // 終了ロクの出力
                if (status == "")
                {
                    // 終了ログ出力
                    LogIF.InfoLog("SERVICE-IF", "正常終了");
                }
                else
                {
                    // 終了ログ出力
                    LogIF.ErrorLog("SERVICE-IF",
                                   "異常終了"
                                   + ":" + status + "\r\n"
                                   + "エラー タイプ:" + errorType + "\r\n" // 2009/09/15-この行
                                   + "エラー メッセージID:" + errorMessageID + "\r\n"
                                   + "エラー メッセージ:" + errorMessage + "\r\n"
                                   + errorToString);
                }
            }

            returnDic.Add("Return", CustomEncode.ToBase64String(ret));
            returnDic.Add("ContextObject", CustomEncode.ToBase64String(contextObject));
            returnDic.Add("ReturnValueObject", CustomEncode.ToBase64String(returnValueObject));

            return(returnDic);
        }