Facing issue while create the events using MS graph API - api

I have tried this code to generate the token:
public async Task Authenticate() {
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent(_clientId), "client_id");
content.Add(new StringContent(_clientSecret), "client_secret");
content.Add(new StringContent("client_credentials"), "grant_type");
content.Add(new StringContent(".default"), "scope");
try {
var task = _client.PostAsync(new Uri(string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", _tenantId)), content);
var res = task.GetAwaiter().GetResult();
if (res.StatusCode == System.Net.HttpStatusCode.OK) {
JsonDocument resJSON = await JsonDocument.ParseAsync(await res.Content.ReadAsStreamAsync());
_accessToken = resJSON.RootElement.GetProperty("access_token").GetString();
lock(this) {
_expiresAt = DateTime.UtcNow.AddSeconds(resJSON.RootElement.GetProperty("expires_in").GetInt16());
}
} else
throw new Exception(res.ReasonPhrase);
} catch (WebException ex) {
// handle web exception
}
}
But I got the error like
error_description=AADSTS1002016: You are using TLS version 1.0, 1.1 and/or 3DES cipher which are deprecated to improve the security posture of Azure AD. Your TenantID is: 334xxxx. Please refer to https://go.microsoft.com/fwlink/?linkid=2161187 and conduct needed actions to remediate the issue. For further questions, please contact your administrator.
Trace ID: c8a502xxxx
Correlation ID: 325a1dxxxxx
Timestamp: 2022-08-04 13:35:23Z
But the same code works in console application.While using this code inside the dll it throws the exception.All the versions are same - .net framework,System.text.json,system.memory etc.
Please help me to sort out this.

According to this page the default TLS version that is used, depends on the targeted .net version and the used operating system.
Targeting .net framework 4.8 should default to TLS1.2 on Windows 10/11
Any change that you are using an older version of either? Or that you are setting the tls version explicitly somewhere in your application?
Also using lock inside an asynchronous method is bad practice and might deadlock your code.

When I use .NET Framework 4.6.1, I encounter the same problem. After I switched the version to 4.7.2, the problem was not solved until I explicitly specified the version in Web.config.
<httpRuntime targetFramework="4.7.2" />

Related

'CspKeyContainerInfo' requires Windows Cryptographic API (CAPI), which is not available on this platform

I have upgraded my project to asp.net core v2.2 from v2.1 and everything was used to work just fine.In the code shown below, I am trying to initilaize an RSA Key for with IdentityServer4(v2.3.2) and while trying to get a token I get the following error.
try
{
var rsaProvider = new RSACryptoServiceProvider(2048);
var rsaParametersPrivate =
RsaExtensions.RsaParametersFromXmlFile(Configuration.GetSection("JwtSettings:rsaPrivateKeyXml")
.Value);
rsaProvider.ImportParameters(rsaParametersPrivate);
var securityKey = new RsaSecurityKey(rsaProvider);
_signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256);
_logger.LogInformation("InitializeRsaKey() successfully executed.");
}
catch (Exception ex)
{
var exception = new Exception("Identity Server RSA Key initialization failed. " + ex);
_logger.LogError(exception, "InitializeRsaKey() method failed.");
throw exception;
}
'CspKeyContainerInfo' requires Windows Cryptographic API (CAPI), which is not available on this platform. error.
Also, my project runs on a CentOS machine meanwhile I develop my project on Windows 10. So, I am aware that something existing in Windows is missing on Linux. To solve the problem any help and suggestion is appreciated.
I digged some github issues and found out that RSACryptoServiceProvider() intherits ICspAsymmetricAlgorithm and this class is supported only on Windows. For details check out here. To fix the problem I have replaced var rsaProvider = new RSACryptoServiceProvider(2048); line with var rsaProvider = RSA.Create(2048); and it works fine with .NET Core v2.2 on CentOS. Hope this helps those who have the same issue.

ASP.NET Core using Azure KeyVault - Error on delegating the KeyVaultClient.AuthenticationCallback

I want to integrate my project on ASP.NET Core 1.0 with Microsoft Azure KeyVault. But it seems like Microsoft.Azure.KeyVault package is not compatible yet with "netcoreapp1.0" framework (I try to download the package using NuGet package manager and the "incompatible package" error message is shown). Therefore I import "net451" framework in the project.json shown in this block:
"frameworks": {
"netcoreapp1.0": {
"imports": [
"net451",
"dotnet5.6",
"portable-net45+win8"
]
}
},
After importing "net451" framework, the error is now gone. Now I want to initiate a new KeyVaultClient class shown in this block:
public void GetKeyVaultSecret()
{
var keyVaultClient = new KeyVaultClient(this.GetTokenAsync);
// ....
}
private async Task<string> GetTokenAsync(string authority, string resource, string scope)
{
var authenticationContext = new AuthenticationContext(authority);
var authenticationResult =
await authenticationContext.AcquireTokenAsync(resource, this.clientAssertionCertificate);
return authenticationResult.AccessToken;
}
The problem is I got this error message on this.GetTokenAsync which I have search the solution for hours without any luck: Argument 1:cannot convert from 'method group' to 'KeyVaultClient.AuthenticationCallback'
If I change
var keyVaultClient = new KeyVaultClient(this.GetTokenAsync);
to:
var keyVaultClient = new KeyVaultClient((authority, resource, scope) => this.GetTokenAsync(authority, resource, string.Empty));
I still got error message: Cannot convert lambda expression to type 'KeyVaultClient.AuthenticationCallback' because it is not a delegate type
Anybody knows how to solve this problem? Thanks.
Regards,
Alvin
The error cannot convert from 'method group' is because you have overloads or extensions (ie more than one method) with the name GetTokenAsync. Try to rename one of them, and it should work.
So after a long time abandoning this question, I've decided to look into it once more thanks to #fernacolo's answer. Turns out that at that time I used version 1.0.0 of the Microsoft.Azure.KeyVault package (which was the latest version back then, shown in Figure 1). Now version 2.0.0 of the package is available and when I find the changelog, I saw this post https://learn.microsoft.com/en-us/azure/key-vault/key-vault-dotnet2api-release-notes which stated that ".NET Core is supported by the 2.0 version of the Azure Key Vault .NET/C# library".
Figure 1. Version history of Microsoft.Azure.KeyVault package
The error is now gone without the need of importing "net451" framework in the project.json.

Can you please provide - Google Bigquery dependency latest Dotnet NUGET package names, because the Bigquery example programs are not working

Need help to get
Google Bigquery dependency latest Dotnet NUGET package names, because the Bigquery example programs are not working and it is giving the dependecy reference expections at IAuthorizationState
eError 1 The type 'DotNetOpenAuth.OAuth2.IAuthorizationState' exists in both 'c:\Echelon\GoogleDownloads\google-api-dotnet-client-1.8.1.source\Src\GoogleApis.Authentication.OAuth2.Tests\bin\Release\DotNetOpenAuth.dll' and 'c:\Users\Srinivasa\Documents\Visual Studio 2013\Projects\BigQueryConsole1\packages\DotNetOpenAuth.OAuth2.Client.4.3.4.13329\lib\net40-full\DotNetOpenAuth.OAuth2.Client.dll' c:\users\srinivasa\documents\visual studio 2013\Projects\BigQueryConsole1\BigQueryConsole1\Program.cs 37 24 BigQueryConsole1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Bigquery.v2;
using Google.Apis.Util;
namespace BigQueryConsole1
{
class Program
{
public static void Main(string[] args)
{
// Register an authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
// Put your client id and secret here (from https://developers.google.com/console)
// Use the installed app flow here.
provider.ClientIdentifier = "asdfasd";
provider.ClientSecret = "asdfasdf";
// Initiate an OAuth 2.0 flow to get an access token
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new BigqueryService(auth);
// Do something with the BigQuery service here
// Such as... service.[some BigQuery method].Fetch();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { BigqueryService.Scopes.Bigquery.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
}
You are using an old version of the library.
The latest NuGet package is available in: http://www.nuget.org/packages/Google.Apis.Bigquery.v2/
Take a look in our samples repository for samples on Google APIs (Unfortunately, we don't have a sample for BigQuery)
You should also take a look in our Getting Started guide and to be more specific in the OAuth 2.0 page.
Good luck!
[UPDATE]
We improved the OAuth 2.0 library significantly. Take a look in our blog announcement from
October 2013 - http://google-api-dotnet-client.blogspot.com/2013/10/announcing-release-of-160-beta-new.html.
In the OAuth 2.0 page I mentioned above there are the exact details of how to set your application to work with Google authorization. The library supports the OAuth 2.0 flows in Windows Phone, Windows 8 application and regular .NET 4.0 and higher.

BundleTransformer.Core throwing implementation exception

I'm trying to use BundleTransformer.Core and BundleTransformer.Less, however I've run into the following exception when trying to setup MVC4 bundles using the recommended code:
Method 'OrderFiles' in type 'BundleTransformer.Core.Orderers.NullOrderer' does not have an implementation.
That exception is thrown on registering the following:
public static void RegisterBundles(BundleCollection bundles)
{
var cssTransformer = new CssTransformer();
var jsTransformer = new JsTransformer();
var nullOrderer = new NullOrderer();
var commonStylesBundle = new Bundle("~/Bundles/CommonStyles");
commonStylesBundle.Include("~/Styles/V3/functions.less",
"~/Styles/V3/helpers.less",
"~/Styles/V3/media-queries.less",
"~/Styles/V3/normalize.less",
"~/Styles/V3/print.less",
"~/Styles/V3/style.less");
commonStylesBundle.Transforms.Add(cssTransformer);
commonStylesBundle.Orderer = nullOrderer;
bundles.Add(commonStylesBundle);
}
I have tried both the latest versions of BundleTransformer.Core and the immediate prior version.
It seems that you have installed preview version of the Microsoft ASP.NET Web Optimization Framework (1.1.0 Alpha1 or 1.1.0 Beta1). At the moment, the Bundle Transformer supports only RTM-version of the Microsoft ASP.NET Web Optimization Framework (version 1.0.0). I recommend that you roll back to RTM-version.

ASP.NET Core and on premise AD authentication

I'd like to try and use ASP.NET Core MVC or Web API at my workplace but we have just Active Directory to authentication and authorization. Is there any solution to solve it with an on premise AD or we have to change for Java? I know this question is not original but I'd like to get a simple answer to it, please.
Microsoft has released pre-release version for System.DirectoryServices. You can get it from NuGet package manager using this command:
Install-Package System.DirectoryServices -Version 4.5.0-preview1-25914-04
This is working fine for me till now.
As of today, System.DirectoryServices is not available in ASP.NET Core yet. You can read more here.
In the meantime, you can use Novell.Directory.Ldap.NETStandard. For example,
public bool ValidateUser(string domainName, string username, string password)
{
string userDn = $"{username}#{domainName}";
try
{
using (var connection = new LdapConnection {SecureSocketLayer = false})
{
connection.Connect(domainName, LdapConnection.DEFAULT_PORT);
connection.Bind(userDn, password);
if (connection.Bound)
return true;
}
}
catch (LdapException ex)
{
// Log exception
}
return false;
}
Since it has too many moving pieces, I have created a sample project at GitHub.