在C#中以编程方式将密钥添加到密钥保管库

时间:2017-10-18 18:16:34

标签: c# azure azure-keyvault

我正在尝试从我在Azure中的密钥保管库中运行的服务中输入一些输出。我的服务输出将是用户凭据,这就是我想为此目的使用Key Vault的原因。

到目前为止,我已经尝试过KeyVaultClient的SetSecretAsync方法,但它不适用于我,我没有收到任何错误信息,但是我也没有看到创建的新秘密我的目标KeyVault。我无法找到KeyVaultClient Add Secret方法,因为它不存在,我在这里使用正确的对象/方法吗?

这里讨论的方法是AddResult。

这是我的代码:

    private static AzureKeyVault instance;
    private static KeyVaultClient client;
    private AzureKeyVault()
    {
        //initialize the azure key vault
        var vaultAddress = ConfigurationManager.AppSettings["VaultUri"];
        client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken));


    }
    public static async Task<string> GetAccessToken(string authority, string resource, string scope)
    {
        var clientId = ConfigurationManager.AppSettings["ClientID"];
        var clientSecret = ConfigurationManager.AppSettings["ClientSecret"];
        ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);

        var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
        var result = await context.AcquireTokenAsync(resource, clientCredential);

        return result.AccessToken;
    }


    public static AzureKeyVault GetInstance
    {
        get
        {
            if (instance == null)
            {
                instance = new AzureKeyVault();
            }
            return instance;
        }
    }

    public void AddResult(string machineIPAndPort, BruteForceResult result)
    {
        client.SetSecretAsync("https://vaultURI(redacted).vault.azure.net/", machineIPAndPort, JsonConvert.SerializeObject(result));
    }

1 个答案:

答案 0 :(得分:10)

耐心等待(等待创作)。

// Let's create a secret and read it back
string vaultBaseUrl = "https://alice.vault.azure.net";
string secret = "from-NET-SDK";

// Await SetSecretAsync
KeyVaultClient keyclient = new KeyVaultClient(GetToken);
var result = keyclient.SetSecretAsync(vaultBaseUrl, secret, "Sup3eS3c5et").Result;

// Print indented JSON response
string prettyResult = JsonConvert.SerializeObject(result, Formatting.Indented);
Console.WriteLine($"SetSecretAsync completed: {prettyResult}\n");

// Read back secret
string secretUrl = $"{vaultBaseUrl}/secrets/{secret}";
var secretWeJustWroteTo = keyclient.GetSecretAsync(secretUrl).Result;
Console.WriteLine($"secret: {secretWeJustWroteTo.Id} = {secretWeJustWroteTo.Value}");

结果:

SetSecretAsync completed:

{  
   "SecretIdentifier":{  
      "BaseIdentifier":"https://alice.vault.azure.net:443/secrets/from-NET-SDK",
      "Identifier":"https://alice.vault.azure.net:443/secrets/from-NET-SDK/59793...",
      "Name":"from-NET-SDK",
      "Vault":"https://alice.vault.azure.net:443",
      "VaultWithoutScheme":"alice.vault.azure.net",
      "Version":"597930b70565447d8ba9ba525a206a9e"
   },
   "value":"Sup3eS3c5et",
   "id":"https://alice.vault.azure.net/secrets/from-NET-SDK/59...",
   "contentType":null,
   "attributes":{  
      "recoveryLevel":"Purgeable",
      "enabled":true,
      "nbf":null,
      "exp":null,
      "created":1508354384,
      "updated":1508354384
   },
   "tags":null,
   "kid":null,
   "managed":null
}

secret: https://alice.vault.azure.net/secrets/from-NET-SDK/59793... = Sup3eS3c5et

你应该做的是重写AddResult()

public bool AddResult(string machineIPAndPort, BruteForceResult result)
{
    await result = client.SetSecretAsync("https://vaultURI(redacted).vault.azure.net/",
        machineIPAndPort, JsonConvert.SerializeObject(result));

    return true;
}

也许可以将其包含在try-catch中并阅读InnerException that's where the meaningful HTTP response body will be以来的 <?php @session_start(); $_SESSION['userid'] = 1; $servername = "localhost"; $username = "root"; $password = ""; $dbname = "stack"; // Create connection $db = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$db) { die("Connection failed: " . mysqli_connect_error()); } $sql1= "SELECT Categoryid, Categoryname, Categorydescription FROM Categories"; $result1 = mysqli_query($db,$sql1); if (!$result1){ echo "<font color = 'Green' .<p> No Category Found, Contact the administrator </p> </font>"; } function safe_insert($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } /* you can validate more than this such as the following string length use preg match to only validate number but l used is_numeric ie if (!preg_match("/^[0-9]*$/",$data)) { return false; } limit post based on day re structure and change mysql to date . table name ie tbl_topic category_id category_description ... you get the idea and many more ................. happy coding */ if (isset($_POST['createtopicbutton'])) { if(isset($_POST['topic_subject']) && isset($_POST['date']) && isset($_POST['topic_category'])){ $state = true; $errors = ''; if(trim($_POST['topic_subject']) == ''){ $errors .= "subject is empty"; $state = false; } if(trim($_POST['date']) == ''){ $errors .= "date is empty"; $state = false; } if(!is_numeric(trim($_POST['topic_category']))){ $errors .= "topic category is should be number"; $state = false; } if($state){ $subject = mysqli_real_escape_string($db , safe_insert($_POST['topic_subject'])); $date = mysqli_real_escape_string($db , safe_insert($_POST['date'])); $topic= mysqli_real_escape_string($db , safe_insert($_POST['topic_category'])); $user_id = mysqli_real_escape_string($db , safe_insert($_SESSION['userid'])); $sql2 = "INSERT INTO Topics(Topic_subject, Topic_date, Topic_category, Topic_by) VALUES('$subject','$date', '$topic', '$user_id')"; $result2 = mysqli_query($db,$sql2); if ($result2){ echo "<font color = 'Green' .<p> Topic Successfully Created </p> </font>"; }else{ echo "<font color = 'Green' .<p> Topic NOT! Successfully Created </p> </font>"; //This is the result I am getting specifically } }else{ echo $errors; } } else{ echo 'Something fishy'; } } ?> <form method = "post" action = "" > <table cellspacing="15"> <tr> <th>Subject </th> <td><input type = "text" name = "topic_subject" /> </td> </tr> <tr> <th>Category </th> <?php echo '<td> <select name="topic_category"> '; while($row = mysqli_fetch_assoc($result1)) { echo '<option value="' . $row['Categoryid'] . '">' . $row['Categoryname'] . '</option>'; } echo '</select></td>'; ?> </tr> <tr> <th>Current Date </th> <td><input type = "text" name = "date" /> </td> </tr> <tr> <th> </th> <td> <input type = "submit" value = "Create Topic!" name = "createtopicbutton" /> </td> </tr> </table> </form> <?php // sample data // /* CREATE TABLE `categories` ( `Categoryid` int(11) NOT NULL, `Categoryname` varchar(255) NOT NULL, `Categorydescription` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `categories` (`Categoryid`, `Categoryname`, `Categorydescription`) VALUES (1, 'fake 1', 'lprem,djbch schjcwdc k'), (2, 'fake 2', 'kjdncsjkc dcjdjkds dskjsdkj'); CREATE TABLE `topics` ( `topic_id` int(11) NOT NULL, `topic_subject` varchar(255) NOT NULL, `topic_date` varchar(255) NOT NULL, `topic_category` int(11) NOT NULL, `topic_by` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `topics` -- INSERT INTO `topics` (`topic_id`, `topic_subject`, `topic_date`, `topic_category`, `topic_by`) VALUES (1, 'sweet', 'chiil', 1, 1), (8, 'jkfdjk', 'kjkjd', 1, 1), (31, 'klds', 'los', 2, 1), (32, 'suceess topic', 'date', 1, 1), (33, 'ksdl', 'sdlksda', 1, 1), (34, 'melody', 'sdjsjssj', 2, 1); -- -- Indexes for dumped tables -- -- -- Indexes for table `topics` -- ALTER TABLE `topics` ADD PRIMARY KEY (`topic_id`); -- -- AUTO_INCREMENT for dumped tables -- */ ?> 。例如,针对密钥保管程序发出请求,我无权访问结果:

InnerException

而且因为这是云,你正在与other mission critical traffic激烈竞争,事情会失败。

相关问题