Asp.Net Core No DefaultChallengeScheme found - c#

I have a custom AuthorizationHandler in my Asp.Net Core API project which authorizes requests based on Tokens been passed in the Headers.
The Handler works fine as in it invoked on runtime however am getting the following error
InvalidOperationException: No authenticationScheme was specified, and there was no
DefaultChallengeScheme found.
I have registered my settings in Startup.cs as follows:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddSingleton<IAuthorizationHandler, TokenAuthorizationHandler>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvc();
}
Any suggestions?

The default properties of the project is enable Anonymous Authentication and disable Windows Authentication .
If you want to choose IIS default authentication as your authenticationScheme , you need to modify the project's properties to enable Windows Authentication and disable Anonymous Authentication :
Right-click the project in Solution Explorer and select Properties.
Select the Debug tab.
Clear the check box for Enable Anonymous Authentication.
Select the check box for Enable Windows Authentication.
Save and close the property page.
Reference : https://learn.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-2.2&tabs=visual-studio#iisiis-express
Or you could add others authenticationSchemes (cookie-based authentication , JWT bearer authentication etc) , refer to Authorize with a specific scheme in ASP.NET Core for more details .

Related

Blazor Server with Microsoft Identity in IIS with virtual application

I've created a Blazor Server project using the standard Visual Studio 2022 template with authentication set to Microsoft Identity. It works locally without issue.
When I try to deploy it to the default website on an IIS server in a virtual application, it gives the following error:
Program.cs:
var builder = WebApplication.CreateBuilder(args);
var initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' ') ??
builder.Configuration["MicrosoftGraph:Scopes"]?.Split(' ');
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();
builder.Services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
I think it is an issue with the return url, because the virtual application name is added to the address automatically. I have this url included in my app registration, but it still doesn't work.
I think after you see the error message page above, you may try to visit http://localhost or maybe you change the default home page url so http://localhost/the_word_you_covered and see if the user already signed in successfully.
I created a new Blazor server application with Microsoft Identity, then I fill the appsettings.json with tenant id, client id, and leave the CallbackPath as /signin-oidc by default. And in AAD, set redirect URL as https://localhost/signin-oidc. It worked well when test locally. After published to IIS, the sign in didn't work well so I comment the
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy
options.FallbackPolicy = options.DefaultPolicy;
});
and content in the so that I can see more error issue.
if (!app.Environment.IsDevelopment()) { }
But after doing these steps, everything worked well except the sign in redirect back to http://localhost/signin-oidc. Pls note here we need to set the redirect URL as http in Azure AD portal because IIS uses HTTP by default. But since there's no page routing to signin-oidc.
=========================================
If what I said above is not the issue, I'm afraid you can create a self-signed certificate and bind it to the default website, then visiting https instead. Just now I tried again and it keep showing 500 error like screenshot below. Then I create self-signed certificate to use https then solved the 500 error.

How to authenticate user in development environment in an ASP.NET Core 3.1 MVC app?

Whenever I implement authentication and authorization with Azure AD in an ASP.NET Core application, in development environments I require a valid and configured account to sign in and get to the protected pages.
If the environment is development, I'd like to be able to run the app as if a user was signed in by default. For example, any User.Identity.IsAuthenticated value would be true, [Authorize] attributes would be ignored, any usages of IAuthorizationService would react as if the user was fully authorized. How could this be done? Or it would be equally good if when I press to sign in with Microsoft it just automatically "authenticates" on any computer.
I looked through some SO solutions, but they all seem to disable authentication. I can't disable it because if [Authorize] attribute is bypassed but User.Identity.IsAuthenticated returns false, code in my controllers and razor views would break. I want this so that when Selenium runs automatic tests for the UI it does not have to deal with signing into Microsoft, and that anyone who wants to run the app locally isn't required to have an account.
When signing in, I use the action from MicrosoftIdentity at /MicrosoftIdentity/Account/SignIn.
If it helps, here's my ConfigureServices method in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
services.Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(Configuration.GetValue<double>("AzureAd:TimeoutInMinutes"));
options.SlidingExpiration = true;
});
RegisterAuthorizationPolicies(services);
services.Configure(OpenIdConnectDefaults.AuthenticationScheme, (Action<OpenIdConnectOptions>)(options =>
{
options.Events.OnTicketReceived = async context =>
{
// I run some code here that determines whether or not to allow the user to sign in.
return;
};
}));
services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
...
}

Asp.Net Core MVC with Windows Authentication on IIS

I have an ASP.NET Core MVC application with Windows Authentication. I published it on IIS server in local network of our company. All works fine, all users log in with their rights. But each time when they open a browser they need to enter their credentials. Each time we see a window for entering the user name and password. How to make a logon automatic?
I added this strings to Startup.cs
public void ConfigureServices(IServiceCollection services)
{
…
services.AddAuthentication(IISDefaults.AuthenticationScheme);
//custom authorization
services.AddAuthorization(options =>
{
options.AddPolicy("Operator", policy => policy.AddRequirements(new CheckADGroupRequirement(Configuration["RolesConfig:Operator"], Configuration["RolesConfig:Manager"])));
options.AddPolicy("Manager", policy => policy.AddRequirements(new CheckADGroupRequirement(Configuration["RolesConfig:Manager"])));
});
services.AddSingleton<IAuthorizationHandler, CheckADGroupHandler>();
//custom authorization
…
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
…
app.UseAuthentication();
…
}
In IIS I set to Enabled only Windows Authentication
The only solution I found it was set Automatic logon in Internet Options but I think it’s bad practice.

Azure AD SSO: .Net Core 2.1 Single Sign On Based On Organization's Office 365 Username&Password

I have created an ASP.NET Core 2.1 MVC web application and I have used a simple login form to authenticate the users. Now We have decided to remove the login form and use a single sign-on option with my Organization's Office 365 user credentials or my office’s outlook username & password and followed the following Microsoft website but I could not choose the right SSO one.
This web app is a MVP (minimum viable product) project so we just don't want to use our own authentication & authorization process and only my organization people going to use this app so we have decided to use the Organization's Azure AD SSO. I am not using SAML or WS-Federation protocols in my web app but I just wanted to implement the SSO for my project.
I searched many sites on the internet, a few websites explained "No code is required to configure SSO but only Azure AD configurations" and some other websites explained with some piece of code also. So now I am totally confused that how should I achieve the SSO for my simple web application.
Hosted environment: Azure App Service
Application users: only organization users (internal web app)
My Startup.cs code:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddSession(options =>
{
options.Cookie.IsEssential = true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//Fetching Connection string from APPSETTINGS.JSON
var ConnectionString = Configuration.GetConnectionString("MbkDbConstr");
//Entity Framework
services.AddDbContext<ShardingDbContext>(options => options.UseSqlServer(ConnectionString));
//Automapper Configuration
AutoMapperConfiguration.Configure();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller:required}/{action}/{id?}",
defaults: new { controller = "UserAccount", action = "UserLogin" });
});
}
}
Note: I have configured the app.UseAuthentication() & other functions but authentication part not used inside my projects.
If you want to Authenticate your users with App Services, refer the document to see how to enable AAD Authentication in app services.
Generally for any web application, you can configure App Registration in Azure AD. You can configure claim attribute as well in order to use SSO feature. Refer the document for how to configure app registration in Azure AD.

AspNetCore Web Api Microsoft Account Authentication

My basic requirement is a Web Api that exposes some REST resources. Authentication is required to access any resource, and I want that to happen via Microsoft Accounts. This is to be a web api for programmatic access.
I started along this path: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/microsoft-logins?view=aspnetcore-2.2
And have got to the end. It probably works fine except I get this:
InvalidOperationException: The default Identity UI layout requires a partial view '_LoginPartial' usually located at '/Pages/_LoginPartial' or at '/Views/Shared/_LoginPartial' to work.
But I don't want a UI with a sign in experience. I want apps (and users from clients such as browsers) to authenticate via Microsoft and then access my REST resources.
My configure services looks like this:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultTokenProviders()
//.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<IdentityDbContext>();
services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.ClientId = _config["Authentication:Microsoft:ApplicationId"];
microsoftOptions.ClientSecret = _config["Authentication:Microsoft:Password"];
});
And then:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseAuthentication();
Program just does:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://localhost:5000", "https://localhost:5001");
You have implemented the Microsoft Authentication AND the login process in the same application, this kind of solution produce a cookie for the ASP.NET.
You probably want clients to authenticate, via OAuth, passing a Bearer Token.
In this case you must use a JwtBearer token authentication.
In this scenario your application DO NOT provide a UI for the authentication (like the example), instead ONLY validate/authenticate the token received.
Here some references
jwt auth in asp.net core
jwt validation
token authenticationin Asp.NET
Authentication in ASP.NET Core JWT

Categories