I'm trying to access Amazon S3 bucket using Amazon Cognito Identity credentials in Xamarin iOS. I have assinged "s3FullAccess" policy to both roles associated with the identity pool.
Code:
CognitoAWSCredentials credentials = new CognitoAWSCredentials("us-west-2:*******-...", RegionEndpoint.USWest2);
IAmazonS3 s3Client; = new AmazonS3Client(credentials, RegionEndpoint.USWest2);
PutObjectRequest putObjectRequest = new PutObjectRequest()
{
BucketName = Constants.AwsS3Bucket,
InputStream = dataStream,
ContentType = contentType,
Key = "fileKey"
};
await s3Client.PutObjectAsync(putObjectRequest).ContinueWith((Task task) => {
if (task.Exception != null) throw (task.Exception);
});
This gives me following exception:
Application Settings exception, Unable to store key CognitoIdentity:IdentityId:us-west-2:*******-..., got error: Param
This error throws when Cognito SDK tries to access the keychain. I managed to fix this error on the simulator by adding a provisioning profile.
Related
ive been trying to retrieve temporary credentials using role arn but getting an error of EC2 Metadata not found in AWS SDK . here is my approach
AssumeRoleRequest request = new AssumeRoleRequest();
request.RoleArn = "arn:aws:iam::532634566192:role/ap-redshift";
request.RoleSessionName = "newsessionanme";
client = new AmazonSecurityTokenServiceClient();
AssumeRoleResponse resp = client.AssumeRole(request);
Console.WriteLine(resp.Credentials);
Console.ReadLine();
2nd approach
client = new AmazonSecurityTokenServiceClient();
var response = client.AssumeRole(new AssumeRoleRequest
{
RoleArn = "arn:aws:iam::532634566192:role/ap-redshift",
RoleSessionName = "newsessionanme"
});
AssumedRoleUser assumedRoleUser = response.AssumedRoleUser;
Credentials credentials = response.Credentials;
This is the error i am getting "Unable to get IAM security credentials from EC2 Instance Metadata Service.'" as also shown in the picture .
enter image description here
I am using Managed Identity to connect to Azure Service Bus and it used to work fine.
This morning, I realized that this approach wasn't working anymore locally (using Visual Studio) and also on the deployed application (using managed identity).
I have a custom token provider class:
public class AzureServicebusManagedIdentityTokenProvider : TokenProvider
{
private const string Resource = "https://servicebus.azure.net/";
protected readonly string TenantId;
public AzureServicebusManagedIdentityTokenProvider(string tenantId = null)
{
TenantId = string.IsNullOrWhiteSpace(tenantId) ? null : tenantId;
}
public override async Task<SecurityToken> GetTokenAsync(string appliesTo, TimeSpan timeout)
{
string accessToken = await GetAccessToken(Resource);
return new JsonSecurityToken(accessToken, appliesTo);
}
private async Task<string> GetAccessToken(string resource)
{
var authProvider = new AzureServiceTokenProvider();
return await authProvider.GetAccessTokenAsync(resource, TenantId);
}
}
Then for example to send a message:
var sbMessageSender = new MessageSender(new ServiceBusConnection("<my connectionstring>")
{
TransportType = TransportType.Amqp,
TokenProvider = new AzureServicebusManagedIdentityTokenProvider("<my tenant id>")
}, "my queue name", RetryPolicy.Default);
var json = JsonConvert.SerializeObject(<message to send>);
var message = new Message(Encoding.UTF8.GetBytes(json));
await sbMessageSender.SendAsync(message);
This error is thrown:
Put token failed. status-code: 401, status-description: InvalidIssuer: Token issuer is invalid. TrackingId:5c6c17c7-7a9e-49f3-adf7-5dbfb35b3daf, SystemTracker:NoSystemTracker, Timestamp:2019-10-29T08:56:17.
I've checked that I have 'Azure Service Bus Data Owner' role and that the 'Azure App authentication' tool in visual studio is set to the appropriate account.
I am using these nuget packages:
Microsoft.Azure.Services.AppAuthentication v1.3.1
Microsoft.Azure.ServiceBus v3.4.0
Not sure If I am doing something stupid (as it used to work ) but any help would be appreciated.
This appears to be due to an issue within Azure. Per the response on my support ticket:
...this issue was caused by the latest service update where there was a syncing issue on the backend subscription ID info for the namespace. This only happens when a namespace is updated. Since RBAC authentication relies on constructing ARM resourceID using the stored subscription ID you saw authentication issues. The issue is now resolved and it should not re-occur.
I'm trying to access Azure Data Fabric V2 programmatically.
First, I had created an App Registration in Azure portal and a Client secret. Then I gave Contributor permission to this App registration on the entire suscription, and also in the resource group where my data factory lives.
Using this credentials I'm able to login to the portal and create an DataFactoryManagementClient
private void CreateAdfClient()
{
var authenticationContext = new AuthenticationContext($"https://login.windows.net/{tenantId}");
var credential = new ClientCredential(clientId: appRegistrationClientId, clientSecret: appRegistrationClientkey);
var result = authenticationContext.AcquireTokenAsync(resource: "https://management.core.windows.net/", clientCredential: credential).ConfigureAwait(false).GetAwaiter().GetResult();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
var token = result.AccessToken;
var tokenCloudCredentials = new TokenCloudCredentials(subscriptionId, token);
datafactoryClient = new DataFactoryManagementClient(tokenCloudCredentials);
}
However, when I try to get my pipeline with
var pipeline = datafactoryClient.Pipelines.Get(resourceGroup, dataFactory, pipelineName);
it throws an error:
System.Private.CoreLib: Exception while executing function:
StartRawMeasuresSync. Microsoft.Azure.Management.DataFactories:
ResourceNotFound: The Resource
'Microsoft.DataFactory/dataFactories/MyPipeline' under resource group
'MyResGroup' was not found.
I had verified that the resource group, the data factory name and the pipeline name are correct, but it keeps throwing this error.
I had the same issue, and it was due to referencing the Nuget package for Azure Data Factory v1 instead of v2.
Version 1: Microsoft.Azure.Management.DataFactories
Version 2: Microsoft.Azure.Management.DataFactory
I need to get access to Key Vault and Service Bus from code, using a Service Principle for authentication.
I can use the following code to access Service Bus, which works as expected - when I enable to Service Principle in the Access Policies I can pull the list of topics:
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(APPID, APPSECRET, TENANTID, AzureEnvironment.AzureGlobalCloud);
var serviceBusManager = ServiceBusManager.Authenticate(credentials, SUBSCRIPTIONID);
var serviceBusNamespace = serviceBusManager.Namespaces.List().SingleOrDefault(n => n.Name == "SERVICEBUSNAMESPACE");
var topics = serviceBusNamespace.Topics.ListAsync().GetAwaiter().GetResult();
However, I also need to get some information from Key Vault and I was trying to establish a common way to authenticate.
METHOD 1
Similar to the above, I tried this code to access KeyVault:
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(APPID, APPSECRET, TENANTID, AzureEnvironment.AzureGlobalCloud);
var kvManager = new KeyVaultClient(credentials);
var secret = kvManager.GetSecretAsync("https://VAULTNAMESPACE.vault.azure.net", "SECRETNAME").GetAwaiter().GetResult().Value;
I get the the following error:
Microsoft.Azure.KeyVault.Models.KeyVaultErrorException: 'Operation
returned an invalid status code 'Unauthorized''
METHOD 2
This code does work for Key Vault however (showing I have correct permissions):
string GetSecret()
{
var client = new KeyVaultClient(GetAccessToken);
var secret = client.GetSecretAsync("https://VAULTNAMESPACE.vault.azure.net", "SECRETNAME").GetAwaiter().GetResult();
return secret;
}
private static async Task<string> GetAccessToken(string authority, string resource, string scope)
{
var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
var credential = new ClientCredential(appId, appSecret);
var tokenResult = await context.AcquireTokenAsync("https://vault.azure.net", credential);
return tokenResult.AccessToken;
}
But, again, it's a very KeyVault specific way to Authenticate and I was hoping to establish a common mechanism using SdkContext.AzureCredentialsFactory. Any reason why I'd be getting an Unauthorized exception with the code above connecting to Key Vault? (all is set up correctly in Azure).
Thanks for any tips!
When you use SdkContext.AzureCredentialsFactory.FromServicePrincipal to authenticate, it will use https://management.azure.com/ as its Resource Uri.
While Azure Key Vault has its own authorization system and its Resource Uri is https://vault.azure.net, so you may get the Unauthorized error message.
So, you could use Method2 to get access to Azure Key Vault with right Resource Uri.
For more details, you could refer to this article.
I am trying to connect amazon S3 + cleversafe with C# , I am using AWSSDK 3.1.0.0.
I want to create a new Bucket.
I have a Provisioning Code = "my provisioning code" , host="my host", accesskey="my access key", secretKey="my secret key"
I tried the following code :
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, error) => { return true; };
BasicAWSCredentials basicCredentials = new BasicAWSCredentials("my access key", "mysecretkey");
AmazonS3Config configurationClient = new AmazonS3Config();
configurationClient.ForcePathStyle = true;
configurationClient.ServiceURL = "https://###.##.###.###";// my host is IPAdress
configurationClient.UseHttp = false;
try
{
using (AmazonS3Client clientConnection = new AmazonS3Client(basicCredentials, configurationClient))
{
PutBucketRequest newBucket = new PutBucketRequest();
newBucket.UseClientRegion = true;
newBucket.BucketName = "NewBucketCleversafe";
PutBucketResponse response = clientConnection.PutBucket(newBucket);
}
}
catch (AmazonS3Exception exception)
{
}
but I get an "Amazon.S3.AmazonS3Exception: A provisioning code must be provided"
also I tried configurationClient.AuthenticationRegion = "my provisioning code"
Where Can I insert it("my provisioning code") in order to fix this Exception? Which Amazon S3 Class, Amazon S3 property should be modified?
Do you know How Can I fix it? any comment or idea could be help. Thanks for your time.
after a meeting with cleversafe he told me that I have to use BucketRegionName.so I used it but I get another Exception message "XML malformed exception " see more detail about it in https://github.com/aws/aws-sdk-net/issues/396(I do not get additional information about it from AWSSDK .net repository).
So conclusion Probably Cleversafe does not support createbucket using AWSSDK #C 3.1.6 3.5 .net