AuthenticationBuilder does not contain a definition for "AddMicrosoftIdentityWebApp" - c#

In the startup.cs file, I tried the following lines to connect the Azure AD B2C into my .Net Core 5 Web-API project followed from a GitHub Repo Here. But it's not accepting the AddMicrosoftIdentityWebApp predefined method in my .Net Core 5+ React template project. Where did I go wrong?
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAdB2C"));
I have tried with OpenId scheme and the following method as well.
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAdB2C"));

I haven't installed the below-given package!.
Microsoft.Identity.Web;

Related

AzureADB2CDefaults obsolete, how do I replace it?

I'm in the process of updating some nuget packages and noticed that AzureADB2CDefaults has been made obsolete. I know that Microsoft.Identity.UI has incorporated AzureADB2C into it but I'm unsure how to use it whilst still referencing AzureADB2C, the code below is whats causing this warning:
services.AddAuthentication(
options =>
{
options.DefaultScheme = AzureADB2CDefaults.AuthenticationScheme;
})
I've tried setting DefaultScheme to just a string of "AzureADB2"
I've also tried adding:
.AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAdB2C"),
Constants.AzureAdB2C, null);
but not having much luck.
Is there any way to reference azure active directory with microsoft identity? Any suggestions on how to replace this bit of code would be much appreciated
Note that: Microsoft.AspNetCore.Authentication.AzureADB2C.UI
Nuget package is obsolete and Microsoft advises to use the
Microsoft.Identity.Web package.
To resolve the issue, install the Latest version of Microsoft.Identity.Web and Microsoft.Identity.Web.UI.
In the startup.cs file replace the below code:
services.AddAuthentication(
options =>
{
options.DefaultScheme = AzureADB2CDefaults.AuthenticationScheme;
})
with
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureADB2C"));
and instead of using services.AddRazorPages(); replace it with services.AddRazorPages().AddMicrosoftIdentityUI();
And also make changes in code by referring to this blog by Andreas Helland.
After making the changes, the code will execute successfully:
For more in detail, refer below links:
Migrating Azure AD B2C integration going from .NET Core 3.1 to .NET 5 by Andreas Helland
Azureb2c login is not connecting to account controller by killswitch

Blazor WebAssembly App with Individual Accounts and ASP.NET Core Hosted - Disable user registration

I have looked at this guide on how to disable registration template in ASP.NET Core:
https://stackoverflow.com/a/58852405/3850405
It is basically a reference to this article:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-5.0&tabs=visual-studio#disable-a-page
Running the command in the server project works fine and everything can be removed. However when you try to Log in again from the client the following error is now present:
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type
'Microsoft.AspNetCore.Identity.SignInManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'
while attempting to activate
'Blazor.Server.Areas.Identity.Pages.Account.LoginModel'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider
sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
Reading up on Standalone or hosted Blazor WebAssembly apps for Scaffold Identity it says:
Client-side Blazor WebAssembly apps use their own Identity UI
approaches and can't use ASP.NET Core Identity scaffolding.
Server-side ASP.NET Core apps of hosted Blazor solutions can follow
the Razor Pages/MVC guidance in this article and are configured just
like any other type of ASP.NET Core app that supports Identity.
The Blazor framework doesn't include Razor component versions of
Identity UI pages. Identity UI Razor components can be custom built or
obtained from unsupported third-party sources.
Given Server-side ASP.NET Core apps of hosted Blazor solutions can follow > the Razor Pages/MVC guidance in this article and are configured just > like any other type of ASP.NET Core app that supports Identity. and that the Server project is ASP.NET Core Hosted I hope it can work.
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-5.0&tabs=visual-studio#standalone-or-hosted-blazor-webassembly-apps
I began seeing the issue when searching for IdentityUser. When running the scaffold a file called IdentityHostingStartup.cs is created that looks like this:
[assembly: HostingStartup(typeof(Blazor.Server.Areas.Identity.IdentityHostingStartup))]
namespace Blazor.Server.Areas.Identity
{
public class IdentityHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices((context, services) => {
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
context.Configuration.GetConnectionString("ApplicationDbContextConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
});
}
}
}
Both cant exist, then Program.cs CreateHostBuilder(args).Build().Run(); will throw this exception:
System.InvalidOperationException: 'Scheme already exists:
Identity.Application'
This is because of the code in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
Removing IdentityHostingStartup.cs still throws the same error.
The key is to look at services.AddDefaultIdentity<IdentityUser> from IdentityHostingStartup.cs and services.AddDefaultIdentity<ApplicationUser> from Startup.cs.
To solve the problem it was not enough to follow the guide from Microsoft. This had to be done as well:
Remove these files:
Blazor\Server\Areas\Identity\IdentityHostingStartup.cs
Blazor\Server\Areas\Identity\Data\ApplicationDbContext.cs
Blazor\Server\wwwroot\favicon.ico
Then edit Blazor\Server\Areas\Identity\Pages\Account\login.cshtml.cs
Change every instance of IdentityUser to ApplicationUser.
Now everything works!
I also got an extra row in appsettings.json - ConnectionStrings called ApplicationDbContextConnection. Simply remove this line as well.
You can also remove these files since they are already present under \Areas\Identity\Pages:
Blazor\Server\Pages\_ViewStart.cshtml
Blazor\Server\Pages\_ViewImports.cshtml
Blazor\Server\Pages\_LoginPartial.cshtml

AddSignIn Method Missing In ASP.NET Core 2.1

I created an ASP.NET Core web application and I tried to add the following code for implementing authentication but the AddSignIn method could not be found.
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddSignIn("AzureAdB2C", Configuration, // This method is missing
options => Configuration.Bind("AzureAdB2C", options));
I am using the Microsoft.AspNetCore.Authentication.OpenIdConnect package so I'm not sure what I'm missing here.
AddSignIn is in the namespace Microsoft.Identity.Web, which is in the package of the same name.
Have you installed the package? https://www.nuget.org/packages/Microsoft.Identity.Web

IIS8.5 .NET Core 3.1 Web API POST - No response externally/on public domain

I have a fully working Web API, as long as I'm making calls from the host environment. If I make a Postman call remotely to my IIS 8.5 server using the public DNS hostname it "Could not get any response".
UPDATE 21/05/2020: I've narrowed the issue down to app.UseHttpsRedirection(), which leads me to believe that the CORS preflight (OPTIONS) request that's sent is being rejected somehow once it enters the server through the redirection middleware. Probably thinks its malicious and rejects but if anyone can provide insight as to why this is, it would be GREATLY appreciated.
Please note the following:
Its a .NET Core 3.1.4 Web API template with two controllers.
These controllers can only perform POST (JSON Data From Body) requests.
I'm using IIS 8.5 on Windows Server 2012 R2, it exists alongside other live .NET framework apps.
I've installed the .NET Core hosting 3.1.4 package on the IIS server.
To visit it an example would be https://localhost/[MyProjectsName]/api/Customers
I've given the app its own dedicated app pool and dedicated identity/user to run on.
I've set .NET CLR version to No Managed Code.
The app is published with dotnet.exe using a TFS2015 build agent with the following arguments
publish "[CSPROJ LOCATION]" -c "TEST" -o "$(build.artifactstagingdirectory)\published" -f "netcoreapp3.1" -r "win81-x64"
I'm using InProcess hosting and specified webBuilder.UseIIS().
I've tried UseUrls("http://*:80;https://*:443") although I fear that's only relevant to Kestrel users.
I've defined <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> within my CSPROJ.
For the sake of troubleshooting I've opened up my CORS policy with the following...
services.AddCors(options =>
{
options.AddPolicy(name: specificOrigins,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowedToAllowWildcardSubdomains();
});
});
...And added app.UseCors(specificOrigins) to the Configure method within Startup.
I've also added [EnableCors("_AllowSpecificOrigins")] attribute to the controllers.
Any help would be greatly appreciated. If more code snippets or info is needed I'll try to update if possible. First time poster, long time lurker, so very unfamiliar with Stack Overflow posting.

Registering NLog as logger for non specific host in dot net core 3.1

I have non web generic host application, according to https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1 I should add logger in .ConfigureLogging but
ConfigureLogging has different prototype for me than it has in docs, ILoggingBuilder doesnt't have for example .ClearProviders()
I can't use .AddNlog() for DI as shown here
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog(); // NLog: Setup NLog for Dependency injection
I think my confusion is caused by not building a web application whereas guides specify configuring NLog for asp.net. Why is NLog different package for web application? Is this caused by NLog automatically logging events released by Kestrel or other web-specific stuff? What's the difference between UseNLog method (which is an extension defined by NLog I presume?) and registering NLog in services as singleton
Both AddNLog() and ClearProviders() are extensions methods. You need to add using namespace along with the relevant nuget-packages.
using NLog.Extensions.Logging;
using Microsoft.Extensions.Logging;
And add these nuget-packages to your project:
https://www.nuget.org/packages/Microsoft.Extensions.Logging
https://www.nuget.org/packages/NLog.Extensions.Logging
ASP.NET Core: https://www.nuget.org/packages/NLog.Web.AspNetCore/ (using NLog.Web)
There are also wiki-pages and examples to be found:
https://github.com/NLog/NLog.Extensions.Logging/blob/master/examples/NetCore2/HostingExample/Program.cs
https://github.com/NLog/NLog/wiki/Getting-started-with-.NET-Core-2---Console-application
https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3

Categories

Resources