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.
Related
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" />
I have some legacy framework code that calls a service that I need to replicate in a .NET Core 3.1 solution. The code uses a client built by adding a web reference (ImageService). The code authenticates the user using Membership and sets an authentication cookie that is used by the execution of client methods.
The method below is what I need to replicate in the Core solution. I've created a client in the .NET Core solution also using the WCF web reference. What do I need to do/use to replicate the functionality of the code below?
private static void setImageService(string host, string userId, string password) {
ImageService.ImageService _imageServiceSoapClient = new ImageService.ImageService();
((ClientFormsAuthenticationMembershipProvider) Membership.Provider).ServiceUri = string.Format("https://{0}/ImageService/Authentication_JSON_AppService.axd", host);
((ClientRoleProvider) Roles.Provider).ServiceUri = string.Format("https://{0}/ImageService/Role_JSON_AppService.axd", host);
bool validateUser = Membership.ValidateUser(userId, password);
if (validateUser) {
AppDomain.CurrentDomain.SetThreadPrincipal(Thread.CurrentPrincipal);
} else {
throw new InvalidCredentialException(string.Format("User {0} not authenticated", userId));
}
_imageServiceSoapClient.CookieContainer = ((ClientFormsIdentity) Thread.CurrentPrincipal.Identity).AuthenticationCookies;
}
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.
I have built a custom Identity.Models framework by simply extending the new asp.net identity framework 2.0 so that I can store the username and other relevant user data in my custom database instead of the default entity database which gets generated and it is working fine.
Now I am building a WCF service from where I would like to authenticate these users and leverage the asp.net identity 2.0 functionalities , but unable to do so.
In my WCF service I made a new Validator class extending UsernamePasswordValidator but it is not working as expected.
public class IdentityValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
using (var context = new MyIdentityDbContext())
{
using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)))
{
var user = userManager.Find(userName, password);
if (user == null)
{
var msg = String.Format("Unknown Username {0} or incorrect password {1}", userName, password);
Trace.TraceWarning(msg);
throw new FaultException(msg);
}
}
}
}
}
Any suggestions would be highly appreciated.
You are almost there, however, you need one more step to tell the WCF service to be well behaved through introducing service behavior, generally in config. For more details, please read
Authentication and Authorization with ASP.NET Identity 2.0 for WCF Services
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.