- Прочитайте секрет из Google Cloud Secret < /li>
Отправить электронное письмо с помощью Сервисная учетная запись, которую я получил из секрета с именем Gmailer_google_service_account .
{
"fortra_account_id": "12345",
"fortra_auth_token": "abcdefghiklmnopqrstuvwxyz",
"emailFrom": "[email protected]",
"email_to": "[email protected],[email protected]",
"gmailer_google_service_account": {
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"client_email": "[email protected]",
"client_id": "110012742384433576204",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/met ... ccount.com",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIB...dLMO3a\n-----END PRIVATE KEY-----\n",
"private_key_id": "some-random-id",
"project_id": "your-project",
"token_uri": "https://oauth2.googleapis.com/token",
"type": "service_account"
}
}
error
Когда я пытаюсь прочитать секрет, это дает мне ошибку на gmailer_google_service_account ; < Br />Unexpected character encountered while parsing value: {. Path 'gmailer_google_service_account. Все сообщение об ошибке: < /p>
Unhandled exception. Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path 'gmailer_google_service_account', line 6, position 39.
at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)
at Newtonsoft.Json.JsonTextReader.ReadAsString()
at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
at FortraCountLicenses.Utils.Secrets.SecretManagerHelper.AccessSecrets() in C:\Users\admin\dotnet\ReadSecret\Utils\Secrets\SecretManagerHelper.cs:line 35
at Program.Main() in C:\Users\admin\dotnet\ReadSecret\Program.cs:line 12
at Program.()
program.cs
// Program.cs
using FortraCountLicenses.Utils.Secrets;
class Program
{
static async Task Main()
{
string logHeadline = "Program·Main·";
// Access secrets
var (fortraAccountId, fortraAuthToken, emailFrom, emailTo, gmailerGoogleServiceAccountJson) = SecretManagerHelper.AccessSecrets();
Console.WriteLine($"{logHeadline} fortraAccountId: {fortraAccountId}");
Console.WriteLine($"{logHeadline} fortraAuthToken: {fortraAuthToken}");
Console.WriteLine($"{logHeadline} emailFrom: {emailFrom}");
Console.WriteLine($"{logHeadline} emailTo: {emailTo}");
Console.WriteLine($"{logHeadline} gmailerGoogleServiceAccountJson: {gmailerGoogleServiceAccountJson}");
var gmailer = new Gmailer(gmailerGoogleServiceAccountJson, emailFrom);
await gmailer.SendEmailAsync(
emailTo: emailTo,
emailSubject: "Hello!",
emailContent: "
Hello, this is a test!
"
);
Console.WriteLine($"{logHeadline} Email sent.");
}
}
utils/secrets/secretmanagerHelper.cs
// Utils/Secrets/SecretManagerHelper.cs
namespace FortraCountLicenses.Utils.Secrets;
using System;
using Google.Cloud.SecretManager.V1;
using Newtonsoft.Json;
using FortraCountLicenses.Utils.GCP;
public class SecretManagerHelper
{
public static (string fortraAccountId, string fortraAuthToken, string emailFrom, string emailTo, string gmailerGoogleServiceAccountJson) AccessSecrets()
{
string logHeadline = "SecretManagerHelper·AccessSecrets·";
string? fortraAccountId = null;
string? fortraAuthToken = null;
string? gmailerGoogleServiceAccountJson = null;
string? emailFrom = null;
string? emailTo = null;
Console.WriteLine($"{logHeadline} Accessing Google Cloud Secret Manager");
var secretReader = new GoogleSecretManagerReader();
string mySecret = secretReader.ReadSecret("fortra-count-licenses");
// Deserialize and extract information from secret
SecretData? secretData = JsonConvert.DeserializeObject(mySecret);
if (secretData == null || string.IsNullOrEmpty(secretData.FortraAccountId))
{
throw new Exception($"{logHeadline} Error: Secret data could not be deserialized or is missing required information.");
}
fortraAccountId = secretData.FortraAccountId;
fortraAuthToken = secretData.FortraAuthToken;
emailFrom = secretData.EmailFrom;
emailTo = secretData.EmailTo;
gmailerGoogleServiceAccountJson = secretData.GmailerGoogleServiceAccount;
return (fortraAccountId, fortraAuthToken, emailFrom, emailTo, gmailerGoogleServiceAccountJson);
}
}
utils/google/googlesecretmanageraccesssecretversion.cs
// Utils/Google/GoogleSecretManagerAccessSecretVersion.cs
namespace FortraCountLicenses.Utils.GCP;
using System;
using Google.Cloud.SecretManager.V1;
public class GoogleSecretManagerReader
{
public string ReadSecret(string secretId, string versionId = "latest")
{
try
{
// Get the project ID from environment variable
string? projectId = Environment.GetEnvironmentVariable("GOOGLE_CLOUD_PROJECT");
if (string.IsNullOrEmpty(projectId))
{
throw new Exception("Project ID not found. Set the 'GOOGLE_CLOUD_PROJECT' environment variable.");
}
// Create the client
SecretManagerServiceClient client = SecretManagerServiceClient.Create();
// Build the secret version name
string secretVersionName = $"projects/{projectId}/secrets/{secretId}/versions/{versionId}";
// Access the secret version
AccessSecretVersionResponse result = client.AccessSecretVersion(secretVersionName);
// Decode the secret data
return result.Payload.Data.ToStringUtf8();
}
catch (Exception ex)
{
Console.WriteLine($"Error accessing secret: {ex.Message}");
return string.Empty;
}
}
}
utils/google/secretdata.cs
// Utils/Google/SecretData.cs
using Newtonsoft.Json;
namespace FortraCountLicenses.Utils.GCP;
using Newtonsoft.Json;
public class SecretData
{
[JsonProperty("fortra_account_id")]
public string? FortraAccountId { get; set; }
[JsonProperty("fortra_auth_token")]
public string? FortraAuthToken { get; set; }
[JsonProperty("email_from")]
public string? EmailFrom { get; set; }
[JsonProperty("email_to")]
public string? EmailTo { get; set; }
[JsonProperty("gmailer_google_service_account")]
public string? GmailerGoogleServiceAccount { get; set; }
}
utils/email/gmailer.cs
using System;
using System.IO;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Newtonsoft.Json;
using MimeKit;
public class Gmailer
{
private readonly string _projectId;
private readonly string _secretId;
private readonly string _emailFrom;
private dynamic _serviceAccountJson;
private GmailService _gmailService;
// Constructor
public Gmailer(string serviceAccountJson, string emailFrom)
{
_serviceAccountJson = serviceAccountJson;
_emailFrom = emailFrom;
AuthenticateServiceAccount();
}
// Authenticate and initialize Gmail service
private void AuthenticateServiceAccount()
{
var credential = GoogleCredential.FromJson(JsonConvert.SerializeObject(_serviceAccountJson))
.CreateScoped(GmailService.Scope.GmailSend)
.CreateWithUser(_emailFrom);
_gmailService = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "FortraCountLicenses"
});
}
// Send Email
public async Task SendEmailAsync(
string emailTo,
string emailSubject,
string emailContent,
string? emailReplyTo = null,
string? attachmentFileName = null,
byte[]? attachmentBytes = null,
string? attachmentMimeType = null)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(_emailFrom, _emailFrom));
message.To.Add(new MailboxAddress(emailTo, emailTo));
message.Subject = emailSubject;
var bodyBuilder = new BodyBuilder { HtmlBody = emailContent };
if (!string.IsNullOrEmpty(emailReplyTo))
{
message.Headers.Add("Reply-To", emailReplyTo);
}
// Add attachment if available
if (!string.IsNullOrEmpty(attachmentFileName) && attachmentBytes != null && !string.IsNullOrEmpty(attachmentMimeType))
{
bodyBuilder.Attachments.Add(attachmentFileName, attachmentBytes, ContentType.Parse(attachmentMimeType));
}
message.Body = bodyBuilder.ToMessageBody();
using var memoryStream = new MemoryStream();
await message.WriteToAsync(memoryStream);
string rawMessage = Convert.ToBase64String(memoryStream.ToArray())
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
var gmailMessage = new Message { Raw = rawMessage };
try
{
var request = _gmailService.Users.Messages.Send(gmailMessage, "me");
var response = await request.ExecuteAsync();
Console.WriteLine($"Email sent successfully to {emailTo}, Message ID: {response.Id}");
}
catch (Exception ex)
{
throw new Exception($"Error sending email: {ex.Message}");
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... dictionary