Send Message to Amazon SQS using credentials in code - amazon-web-services

Trying to post a message to an AWS SQS Queue that already exists using .Net Core.
Due to some deployment issues, I don't want to create a separate credentials file, I just want to manually add the credentials and add them to my client or request. I can't see how to do this using the documentation.
I've got a simple console app version of what I am trying to do below... I have created the Credentials, I just can't see how to inject them into the client or request so that it authenticates with my IAM user.
Currently the code just hangs creating the client.
var awsCreds = new BasicAWSCredentials("MYKEYGOESHERE", "MYSECRETGOESHERE");
var amazonSQSConfig = new AmazonSQSConfig();
amazonSQSConfig.ServiceURL = "https://sqs.eu-west-1.amazonaws.com";
var amazonSQSClient = new AmazonSQSClient(amazonSQSConfig);
var sendRequest = new SendMessageRequest();
sendRequest.QueueUrl = "https://sqs.eu-west-1.amazonaws.com/[USERID]/[QUEUENAME]";
sendRequest.MessageBody = "{ 'message' : 'hello world' }";
var sendMessageResponse = amazonSQSClient.SendMessageAsync(sendRequest);

You have to pass the credentials to the AmazonSQSClient like so:
var amazonSQSClient = new AmazonSQSClient(awsCreds, amazonSQSConfig);

Five years later, here is what is working for me:
AmazonSQSClient sqsClient = new AmazonSQSClient("MYKEYGOESHERE", "MYSECRETGOESHERE", RegionEndpoint.USWest2);
No use of BasicAWSCredentials or AmazonSQSConfig.

Related

How to request response from .net core to aws amplify GraphQL

Recently, I'm working on AWS Amplify, Which has java and javaScripts related example, but no .net related example. after next i solved this below the way. Here is my question this is the only process to request or response, another way that i missed.
const string query = "query ";
var serializer = new NewtonsoftJsonSerializer();
using var graphQlClient = new GraphQLHttpClient("https://xx.xx.xx.amazonaws.com/graphql", serializer);
graphQlClient.HttpClient.DefaultRequestHeaders.Add("x-api-key", "<api key>");
var subscriptionStream = await graphQlClient.SendQueryAsync<dynamic>(query);
I expect a better way, except my current code.

Authenticating with AWS .NET SDK for Amazon Chime

I'm trying to create meeting using Chime SDK and I'm passing accessKey and accessKeyId to authenticate. However, the request fails with error, 'Invalid session token'. When I pass session token generated using AWS CLI it works fine. I want to generate the session token programmatically from within .net. How to achieve this.
AWSCredentials credentials = new Chime.Credentials(awsAccessKeyId, awsSecretAccessKey, token);
RegionEndpoint region = RegionEndpoint.USEast1;
client = new AmazonChimeClient(credentials, RegionEndpoint.USEast1);
CreateMeetingRequest request = new CreateMeetingRequest();
request.MeetingHostId = meetingHostId;
request.ExternalMeetingId = externalMeetingId;
return await client.CreateMeetingAsync(request);
You are not setting the ClientRequestToken
CreateMeetingRequest request = new CreateMeetingRequest();
request.MeetingHostId = meetingHostId;
request.ExternalMeetingId = externalMeetingId;
//needs request.ClientRequestToken = ????
Tim

WebJobs storage with Managed Identity

By default WebJobs requires to specify Azure Storage account using AzureWebJobsStorage connection string.
But I already have access to my storage with Managed Identity:
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://storage.azure.com/");
StorageCredentials storageCredentials = new StorageCredentials(new TokenCredential(accessToken));
CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(storageCredentials, "mystorageaccount", "core.windows.net", true);
Can I configure WebJobs to use this cloudStorageAccount instead of AzureWebJobsStorage connection string?
Can I configure WebJobs to use this cloudStorageAccount instead of AzureWebJobsStorage connection string?
Yes, you could use cloudStorageAccount to get blob account and do some operation on blobs. However, you still need to provide AzureWebJobsDashboard and AzureWebJobsStorage when you use Webjob. Because they are not only connectionstring, they are also the log path.
In my test, I set AzureWebJobsStorage value with storage1 connection and in code I get storage2 account and it works.
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://storage.azure.com/").Result;
StorageCredentials storageCredentials = new StorageCredentials(new TokenCredential(accessToken));
CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(storageCredentials, "storage2", "core.windows.net", true);
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("mycontainer");
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference("hello.txt");
cloudBlockBlob.UploadTextAsync("aaaaaaaa").Wait();
For more details about assign role and get access token you could refer to this article.

Authenticate for Google Cloud PubSub using parameters from a config file in c#.net

I am following this sample in attempt to publish messages in PubSub from a c#.net app on a windows server. As expected it throws auth exception on:
PublisherClient publisher = PublisherClient.Create();
Most of my code base connects to GCS and BigQuery using their respective services, sample below:
private StorageService GetStorageService()
{
X509Certificate2 certificate = new X509Certificate2(certificateFile, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { StorageService.Scope.DevstorageFullControl }
}.FromCertificate(certificate));
return new StorageService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = projectNumber,
});
}
I just pass certificateFile, serviceAccountEmail from a config file as parameters. Is there anyway to Auth similarly for PubSub?
Yes, it's possible, and you're looking in the right repo for samples. I notice the QuickStart directory is missing a README.md. I'll add one shortly.
To get this line of code to work:
PublisherClient publisher = PublisherClient.Create();
Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of a json service account credentials file. Details are in step 3 of the root README:
https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/master/README.md
If your environment requires you to manually specify the path to a credential file, the code looks like this:
GoogleCredential googleCredential = null;
using (var jsonStream = new FileStream(jsonPath, FileMode.Open,
FileAccess.Read, FileShare.Read))
{
googleCredential = GoogleCredential.FromStream(jsonStream)
.CreateScoped(PublisherClient.DefaultScopes);
}
Channel channel = new Channel(PublisherClient.DefaultEndpoint.Host,
PublisherClient.DefaultEndpoint.Port,
googleCredential.ToChannelCredentials());
PublisherClient publisher = PublisherClient.Create(channel);
I reported issue https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/1398 to make this common task simpler.

New Google Drive Directory APIs error out: Bad request

I am using below piece of code to list all domain users in my simple Console application
var certificate = new X509Certificate2("D:\\3acf2c2008cecd33b43de27e30016a72e1482c41-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable);
var privateKey = certificate.Export(X509ContentType.Cert);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = "877926787679-b7fd15en1sh2oc65e164v90cfcvrfftq#developer.gserviceaccount.com",
Scope = DirectoryService.Scopes.AdminDirectoryUserReadonly.GetStringValue(),
ServiceAccountUser = "user1#05.mygbiz.com"
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
DirectoryService dirService = new DirectoryService(new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "My APP"
});
Users users = dirService.Users.List().Execute();
Execute() method errors out saying Bad Request.
Questions:
How to overcome this issue?
Does this Admin SDK support trial version of Google APP account?
I have updated service account Client ID in Google Console and also updated in Admin Console with below scopes
https://www.googleapis.com/auth/admin.directory.group
https://www.googleapis.com/auth/admin.directory.user
and also set API access check box. Do I missing something in settings?
Like JoBe said, you should include the domain parameter.
happy_user = service.users().list(domain='mydomain.com').execute()
This has worked for me.