AcquireTokenByUsernamePassword throws System.AggregateException and MsalServiceException - .net-core

AcquireTokenByUsernamePassword throws System.AggregateException and MsalServiceException:
1st Exception:
System.AggregateException: 'One or more errors occurred. (Federated
service at
https://autologon.microsoftazuread-sso.com/domain.com/winauth/trust/2005/usernamemixed?client-request-id=[ID]
returned error: Authentication Failure )'
2nd Exception:
MsalServiceException: Federated service at
https://autologon.microsoftazuread-sso.com/domain.com/winauth/trust/2005/usernamemixed?client-request-id=[ID]
returned error: Authentication Failure
string clientId = "client-id";
string tenant = "tenant-id";
// Open connection
string authority = "https://login.microsoftonline.com/" + tenant;
string[] scopes = new string[] { "user.read" };
IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.Build();
var securePassword = new SecureString();
foreach (char c in user.Password.ToCharArray()) // you should fetch the password
securePassword.AppendChar(c); // keystroke by keystroke
var results = app.AcquireTokenByUsernamePassword(scopes, user.UserName, securePassword).ExecuteAsync().Result.IdToken;

Your scope is set incorrectly. I think you want to call your custom api instead of ms graph api, so you should get a token for your expose api. The scope you set in the code is the permissions of ms graph api instead of your custom api scope.
Therefore, you need to set the scope to: api://{api app client id}/.default.

Related

NServiceBus - Cannot access a disposed object. Object name: 'Transaction'.'

I am getting the Cannot access a disposed object. Object name: 'Transaction'.' error message when I try to call sendlocal method.
In the handler, I am making a cosmos DB call to get the required information before calling this sendlocal method.
public async Task Handle(OrderCommand message, IMessageHandlerContext context)
{
//Cosmos DB call to get the required information
var requiredInfo = await cosmosClient.GetInformation(message.Id);
await context.SendLocal(requiredInfo);
}
And below is the service bus configuration sample code
var endpointConfiguration = new EndpointConfiguration(endpointName);
var transport = endpointConfiguration.UseTransport<AzureServiceBusTransport>();
transport.ConnectionString(GetTransportConnectionString(configuration));
//transport.Transactions(TransportTransactionMode.TransactionScope);
endpointConfiguration.UseSerialization<NewtonsoftSerializer>();
endpointConfiguration.UsePersistence<CosmosPersistence>()
.CosmosClient(new CosmosClient(cosmosConnectionString))
.DatabaseName(configuration.GetConnectionString("DATABASENAME"))
.DefaultContainer(containerName: "sagastore", partitionKeyPath: "/id")
.DisableContainerCreation();
endpointConfiguration.SendFailedMessagesTo("error");
endpointConfiguration.AuditProcessedMessagesTo("audit");
endpointConfiguration.AuditSagaStateChanges(serviceControlQueue: "audit");
endpointConfiguration.EnableInstallers();

AWS AmazonSimpleSystemsManagementClient cannot read credentials in .NET Framework application

I have .NET Framework application where I try to read data from AWS parameter store using AmazonSimpleSystemsManagementClient on my local environment. Besides I have credentials generated by AWS CLI and located in
Users/MyUser/.aws
folder. When I try to connect to the parameter store from CMD using the creds it works fine. Though the AmazonSimpleSystemsManagementClient in the application with default constructor, it throws exception "Unable to get IAM security credentials from EC2 Instance Metadata Service." When I tried to pass BasicAWSParameters to the client with hardcoded working keys I got another exception "The security token included in the request is invalid".
Also I tried installing EC2Config, initializing AWS SDK Store from Visual Studio AWS Toolkit. Though it didn't change the game.
I would want to avoid using environment variables or hardcoding the keys since keys are generated and valid only 1 hour. Then I should regenerate so copying them somewhere every time is not convenient for me.
Please advice how to resolve the issue.
Some code
_client = new AmazonSimpleSystemsManagementClient()
public string GetValue(string key)
{
if (_client == null)
return null;
var request = new GetParameterRequest
{
Name = $"{_baseParameterPath}/{key}",
WithDecryption = true,
};
try
{
var response = _client.GetParameterAsync(request).Result;
return response.Parameter.Value;
}
catch (Exception exc)
{
return null;
}
}
credentials file looks as following (I removed key values not to expose):
[default]
aws_access_key_id= KEY VALUE
aws_secret_access_key= KEY VALUE
aws_session_token= KEY VALUE
[MyProfile]
aws_access_key_id= KEY VALUE
aws_secret_access_key= KEY VALUE
aws_session_token= KEY VALUE
As long as you have your creds in .aws/credentials, you can create the Service client and the creds will be located and used. No need to create a BasicAWSParameters object.
Creds in a file named credentials:
[default]
aws_access_key_id=Axxxxxxxxxxxxxxxxxxxxxxxxxxx
aws_secret_access_key=/zxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This .NET code works.
using System;
using System.Threading.Tasks;
using Amazon.SimpleSystemsManagement;
using Amazon.SimpleSystemsManagement.Model;
namespace ConsoleApp1 {
class Program {
static async Task Main(string[] args) {
var client = new AmazonSimpleSystemsManagementClient();
var request = new GetParameterRequest()
{
Name = "RDSConnection"
};
var response = client.GetParameterAsync(request).GetAwaiter().GetResult();
Console.WriteLine("Parameter value is " + response.Parameter.Value);
}
}
}

An exception of type 'System.ArgumentException' occurred in Google.Apis.dll but was not handled in user code

I am trying to connect Google Drive Service client but I am getting this exception and I am not getting any solution. Here is my code.
public static DriveService GetDriveClient()
{
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets { ClientId = clientID, ClientSecret = clientSecret }
, scopes
, Environment.UserName
, CancellationToken.None
, new FileDataStore(credPath, true)
).Result;
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = appName,
});
return service;
}
I am getting following error in yellow screen:
Invalid Application name
Parameter name: ApplicationName
The appName value you are using to set ApplicationName is invalid.
ApplicationName is used directly in the HTTP User-Agent header, so must conform to the token specification in on RFC2616 page 17.
As of release v1.27.0 this uses the System.Net.Http.Headers.ProductInfoHeaderValue.TryParse() method to check validity. See BaseClientService.cs line 120
.NET doesn't like any special characters in the Application Name.
I copied code from the Google API Quickstart and continually received errors.
//static string ApplicationName = "Drive API .NET Quickstart"; //DOESN'T WORK!
static string ApplicationName = "oneWord"; //WORKS!
Possibly needs URL encoding or some other handling but the above fixed my problem.

Office 365 Rest Api Having issues getting access token

So far i have this.
public static async Task<OutlookServicesClient> CreateOutlookClientAsync(string capability)
{
try
{
string authority = CommonAuthority;
// Create an AuthenticationContext using this authority.
_authenticationContext = new AuthenticationContext(authority);
//See the Discovery Service Sample (https://github.com/OfficeDev/Office365-Discovery-Service-Sample)
//for an approach that improves performance by storing the discovery service information in a cache.
DiscoveryClient discoveryClient = new DiscoveryClient(
async () => await GetTokenHelperAsync(_authenticationContext, DiscoveryResourceId));
// Get the specified capability ("Contacts").
CapabilityDiscoveryResult result =
await discoveryClient.DiscoverCapabilityAsync(capability);
var client = new OutlookServicesClient(
result.ServiceEndpointUri,
async () =>
await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId));
return client;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
if (_authenticationContext != null && _authenticationContext.TokenCache != null)
_authenticationContext.TokenCache.Clear();
return null;
}
}
}
private static async Task<string> GetTokenHelperAsync(AuthenticationContext context, string resourceId)
{
string accessToken = null;
AuthenticationResult result = null;
string myId = WebConfigurationManager.AppSettings["ida:ClientID"];
string myKey = WebConfigurationManager.AppSettings["ida:Password"];
ClientCredential client = new ClientCredential(myId,myKey);
result = await context.AcquireTokenAsync(resourceId, client);
//result =context.AcquireToken(resourceId, ClientID,_returnUri);
accessToken = result.AccessToken;
return accessToken;
}
When i get to result one of two things happen if i user AcquireTokenAsync i get an error stating Application with identifier XXXX was not found in directory api.office.com otherwise if i run AcquireToken i get the login modal to pop but an error occurs indicating the request must contain client_secret .
I have no idea how to resolve this issue i suspect it may have something to do with the actual app configuration i have tried both creating my own app in Azure AD and using VS Connected Service, Has Anyone Else ran into a similar issues?
Based on the errors you're seeing, there seems to be an issue with how your app is registered. The first error usually happens when the app is not marked as multi-tenant, and you login to the app with a tenant other than the one where the app is registered.
The second error is odd. Client secret is what you're reading out of the ida:Password element and passing in the ClientCredential object.
I just put a .NET tutorial up yesterday that walks through setting this stuff up. Take a look and see if that helps get you unblocked.

Web request to 'https://accounts.google.com/o/oauth2/token' failed. No connection could be ...target machine actively refused it 173.194.70.84:443

I am building an application to fetch data via google analytics. For that purpose I have created a service account information from Google API console and in my .NET webform application successfully able to fetch data via following code:
string clientEmailId = ConfigurationManager.AppSettings.Get("clientEmailId");
string keyFile = AnalyticsKeyFileInitialPath + ConfigurationManager.AppSettings.Get("keyFile");
string keyPass = ConfigurationManager.AppSettings.Get("keyPass");
var desc = GoogleAuthenticationServer.Description;
var key = new X509Certificate2(keyFile, keyPass, X509KeyStorageFlags.Exportable);
var client = new AssertionFlowClient(desc, key) { ServiceAccountId = clientEmailId, Scope = scopeUrl };
var auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
var gas = new AnalyticsService(new BaseClientService.Initializer
{
Authenticator = auth
});
//auth.LoadAccessToken();
var accounts = gas.Management.Accounts.List().Fetch();
Now I am calling same code via WCF service but getting following error
Exception Message: Unable to connect to the remote server
Inner Exception: Web request to 'https://accounts.google.com/o/oauth2/token' failed.
Inner Exception: No connection could be made because the target machine actively refused it 173.194.70.84:443
Any idea what I could be doing wrong?

Resources