.net core authentication using System.DirectoryServices - authentication

I want to implement active directory authentication in my .net core application.
When I read https://github.com/dotnet/corefx/issues/2089 this mentions that out of the box System.DirectoryServices is not supported by .net core. So as per the post I added preview for System.DirectoryServices.AccountManagement.
After adding this how do I create a ldap connection. I am not able to create a one as it always returns null or gives object reference error.
I try to create connection as:
var context = new PrincipalContext(ContextType.Domain, "xx.com", username, password);
Any help is appreciated

Related

Blazor throwing error when using HttpContext

I want to get current windows user name when user opens the website. My application uses Blazor server-side. To get current username, I added:
In startup.cs:
services.AddHttpContextAccessor(); (under
ConfigureServices)
In razor page:
#inject IHttpContextAccessor httpContextAccessor
In razor page method:
string userName = httpContextAccessor.HttpContext.User.Identity.Name;
When I execute the code, the application throws an exception:
"An error has occurred. This application may no longer respond until reloaded."
I get this error only when I deploy on IIS. On local machine it works well.
I had a similar issue trying to access HttpContext for user information using Blazor. I found this here which was a life saver. HttpContext is NULL when running web app in IIS
All I had to do to solve the problem was to enable WebSockets in IIS.
Here are the steps: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-3.1#iisiis-express-support
If you were to change that string from
string userName = httpContextAccessor.HttpContext.User.Identity.Name
to
string userName = httpContextAccessor?.HttpContext?.User?.Identity?.Name??"Anonymous"
then it would probably work.
It's because your IIS settings are allowing anonymous access and so your Identity object is null.
You should check for the inner exceptions behind the application crash but that will be your issue. You need to prevent anonymous access on IIS to get the Windows authentication passed through.
To manage IIS refer here https://stackoverflow.com/a/5458963/12285843

Any luck in using AddMicrosoftIdentityWebApp in combination with IdentityServer4?

I'm trying to get Microsoft configured as an external login provider in Identityserver4.
I succeeded by following identity server's documentation with using AddMicrosoftAccount:
services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
microsoftOptions.ClientId = configuration["MicrosoftLoginProvider:ClientId"];
microsoftOptions.ClientSecret = configuration["MicrosoftLoginProvider:ClientSecret"];
});
However, I didn't have luck with getting single sign-out to work. The documentation is in line with Microsoft's documentation at https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/microsoft-logins?view=aspnetcore-5.0.
However, if you follow the instructions to create an app in Microsoft Developer Portal (portal.azure.com), the sample code on that portal suggests a different way. The sample application that the portal generated for me (WebApp-OpenIDConnect-DotNet) is using AddMicrosoftIdentityWebApp:
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
Since this application is working out-of-the-box including single sign-out, Iam wondering if this is the way I have to continue.
To my surprise, however, I can't find any doc/blogs about how to integrate this approach in IdentityServer4. I almost got it to work myself, but there are a few weird issues.
Can someone clarify if using AddMicrosoftIdentityWebApp is the way to go to add Microsoft as an external identity provider to Identityserver4?
Has someone succeeded in getting AddMicrosoftIdentityWebApp to work with IdentityServer4?
THanks for your help!
I figured how to get it to work.
Actually, only two things I had to do.
First, I had to remove OpenIdConnectDefaults.AuthenticationScheme in the call to AddAuthentication in the example code that Microsoft generated. So the code becomes:
services.AddAuthentication()
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
Then, in the code that reads the external identity from a temporary cookie, I had to use CookieAuthenticationDefaults.AuthenticationScheme. So, that code now reads as follows:
var authenticationResult = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
That was all.
After digging around I found this statement here:
Microsoft.Identity.Web is a simpler way to use Azure AD in ASP.NET Core web apps and web APIs.
It doesn't replace ASP.NET Identity in any way, it doesn't replace AddJwtBearer or AddCookie or any of the lower level primitives, but it does use and configure them correctly for Azure AD.
It doesn't work with non-Azure identity providers. It replaces AzureAD.UI and AzureADB2C.UI which are obsolete in .NET 5.0
So, the conclusion is that Microsoft.Identity.Web does not work outside Azure AD and hence not with IdentityServer.
If you do get it to work then let me know!

How to register middle-ware for a Custom Asp.Net Identity Storage Provider using ASP-5 / MVC-6 / Identity 3

I am trying to upgrade an Asp.Net Identity 2 'custom storage provider' to work with Identity 3 beta 4 in Visual Studio 2015, with the default MVC6 template.
I'm having difficulty learning how to register the Asp.Net Identity 3 custom storage provider with ASP5 middleware.
At the moment I have done the following, but not sure if it is correct:
services.AddIdentity()
.AddRoleStore>()
.AddUserStore>()
.AddDefaultTokenProviders();
I'm not sure how I also register the database context?
In my project is is called MySQLDatabase.cs
I cannot find any documentation.
Registering Identity.EntityFramework middle-ware seems to be done differently to a custom storage provider.
I receive the following error when running the default MVC6 template and clicking the 'register' button:
"InvalidOperationException: Unable to resolve service for type 'Bondii.Identity.MySQL.MySQLDatabase' while attempting to activate 'Bondii.Identity.MySQL.UserStore`1[Bondii.Identity.MySQL.IdentityUser]'."
My Code including full project:
GitHub repository to see my code is:
https://github.com/simonpbond/bondii.identity.mysql
The original 'custom storage provider tutorial based on Identity 2 - I am trying to upgrade to Identity 3:
http://www.asp.net/identity/overview/extensibility/implementing-a-custom-mysql-aspnet-identity-storage-provider.
The original example code:
https://aspnet.codeplex.com/SourceControl/latest#Samples/Identity/AspNet.Identity.MySQL/
In your startup.css you need something like:
services.AddTransient(_ => new MySQLDatabase());
Before:
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddRoleStore<MySQL.RoleStore<IdentityRole>>()
.AddUserStore<MySQL.UserStore<IdentityUser>>()
.AddDefaultTokenProviders();
This will give you a database connection per request i believe and will be passed to the constructor of your Stores by the DI.
This may not be the best way, it may be better to pass some sort of factory as a singleton but this should work the way you have it setup.

Creating ASP.NET MVC4 project to connect to SiteCore Master for Admin Access

I have a SiteCore 6.5 already installed, and I just want to create a simple ASP.NET MVC4 application that will connect to the Sitecore\Admin, and allow me to call Context.GetItem("/sitecore/content/home") function call. Is there an easy of doing this? What do I have to change in the web.config to make this happen? This is used as a simple Admin toolbox app, so all of the username and password are hardcoded for the connection, and I am just using the SecurityDisabler() and UserSwithcher() to run the function under Admin.
Take a look at the Sitecore Item Web API module, it's available on the SDN. The API gives access to content through items paths, IDs, and Sitecore queries.
The Item Web API was the subject of a presentation at this month's London User Group meeting. You can find a recording of the presentation on YouTube and the demo code is available on GitHub.
If you want to understand what is required to use the standard Sitecore API's to access content items outside of the website context Mike Edwards has a great post on How to configure Sitecore 6.5 to work in NUnit. This post explains what configuration will be required in the caller to access Sitecore without a context and it will then be possible to execute code like the following:
using NUnit.Framework;
using Sitecore.Data;
using Sitecore.Data.Items;
[TestFixture]
public class when_connecting_to_sitecore_master_database
{
[Test]
public void it_can_retrieve_the_root_item()
{
Database db = global::Sitecore.Configuration.Factory.GetDatabase("master");
Item item = db.GetItem("/sitecore");
Assert.IsNotNull(item);
Assert.AreEqual("sitecore", item.Name.ToLower());
}
}
I was able to connect a MVC 4 app to the Sitecore 6.5 installation for some admin implementations. I just copied the entire folder for App_Config and Web.Config file to the MVC app, and the start to migrate the MVC4 web.config into the copied web.config from the installations. I then started to take out pieces one at a time, most of the part that you should take out will show up in the as error when you run the application, but the main part that we giving me an error was the httpredirection to the sitecore installation, and that was the httphandlers tag and httpModules tag, and my MVC app showed right now, and I was able to connect to the Sitecore configuration and factory.

ASP.NET Web API Sample Membership Authentication - Azure DB Initialization

I created a brand new MVC 4 Project (using Web Api Template, not Internet template). How can I initialize the simple membership database at first run exactly as the internet template does? What I did so far:
created brand new MVC 4 Project -> Web Api Template
implemented the filter InitializeSimpleMembershipAttribute.cs and decorated the HomeController with it.
added the model AccountModels.cs
added enabled="true" attribute to roleManager under system.web in web.config
the connection string is pointing to SQL Azure and working fine
When I run this app for the first time, the database is created but are created just 1 table in it: UserProfile, all the other tables: webpages_Membership, webpages_Roles ... are missing. There are no errors nothing.
All I need is to be able that when my MVC4 Project (Web Api Template) runs for the first time, will ensure that the SampleMembership db and tables are created. In order to be able to authenticate a client rest call using membership authentication.
Please let me know if this is the right path.
Have you checked if the connection string name in the web.config is defined
in AccountModels.cs for the usercontext
in InitializeSimpleMembershipAttribute.cs for the database initialization