xaf-environment-auth
Skill4 starsChanged 6 months agoMITView on GitHub
Configure DevExpress XAF Blazor authentication to switch between SSO (Windows Authentication) and standard username/password login based on ASPNETCORE_ENVIRONMENT — not Debug/Release build configuration. Use when setting up XAF for multi-environment deployment (Production = SSO, Test = password, Development = password), troubleshooting "SSO works in IIS but not in dev", or carving out a service-account exception for Hangfire jobs that must password-authenticate. Covers the runtime environment switch, appsettings.{Environment}.json layering, HangfireJob service-user pattern, HidePasswordLogonController, and where ASPNETCORE_ENVIRONMENT must (and must not) be set. Triggers: XAF SSO, XAF Windows Authentication, ASPNETCORE_ENVIRONMENT XAF, HidePasswordLogonController, appsettings.Production.json XAF, XAF auth per environment, HangfireJob service account.
In this repository11 other files it gives its agents.
- devexpress-xaf-dockerSkill
- xaf-blazor-startupSkill
- xaf-conditional-appearanceSkill
- xaf-easytest-authoringSkill
- xaf-efcore-entitiesSkill
- xaf-hangfire-jobsSkill
- xaf-navigation-hubSkill
- xaf-playwright-testingSkill
- xaf-reportingSkill
- xaf-search-panelsSkill
- xaf-securitySkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 60
Never: put it in appsettings.json.
- Very specific: line 120
Always register password authentication, even in Production.
- Distinctive: line 231
When auth misbehaves, check in this order:
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
XAF Environment-Based Authentication Mode
The Anti-Pattern: #if DEBUG
// WRONG — compile-time switch
#if DEBUG
services.AddXafAuthentication().AddPasswordAuthentication();
#else
services.AddXafAuthentication().AddWindowsAuthentication();
#endifThis breaks the moment anyone builds Release locally (no domain controller → can't log in) or runs Debug in test (gets password login when policy says SSO). Build configuration is not deployment intent.
The Pattern: Runtime Environment
ASPNETCORE_ENVIRONMENT decides auth mode. ASP.NET Core reads it before config and uses it to pick which appsettings.{Environment}.json to layer over appsettings.json.
| Environment | Auth mode | Hangfire | Source |
| Production | SSO; password blocked for humans | Enabled | appsettings.Production.json |
| Test | Username/password | Enabled | appsettings.Test.json |
| Development | Username/password | Disabled | appsettings.Development.json |
The runtime selector is config-driven, with an env-based default:
public static class AuthenticationMode
{
private const string UseSingleSignOnKey = "Authentication:UseSingleSignOn";
public static bool UseSingleSignOn(IConfiguration configuration, IHostEnvironment environment)
{
var configured = configuration.GetValue<bool?>(UseSingleSignOnKey);
if (configured.HasValue) return configured.Value;
return environment.IsProduction(); // default
}
}The explicit Authentication:UseSingleSignOn key beats the environment default — useful for an SSO-disabled staging that runs on ASPNETCORE_ENVIRONMENT=Production.
Where to Set ASPNETCORE_ENVIRONMENT
Never put it in appsettings.json. ASP.NET Core reads the variable before any config file is loaded, so a value inside appsettings.json is ignored for environment selection.
Set it via:
- IIS:
web.config<environmentVariables>element under<aspNetCore>. - Windows services: service environment block or
setx ASPNETCORE_ENVIRONMENT Test /M. - Docker:
ENV ASPNETCORE_ENVIRONMENT=Testin Dockerfile or-e ASPNETCORE_ENVIRONMENT=Test. - Visual Studio: launch profile in
Properties/launchSettings.json.
IIS web.config:
<aspNetCore processPath="dotnet" arguments=".\WLNCentral.Blazor.Server.dll"
stdoutLogEnabled="false" hostingModel="inprocess">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
</environmentVariables>
</aspNetCore>Wiring in Startup.cs
public class Startup
{
public Startup(IConfiguration configuration, IHostEnvironment env)
{
Configuration = configuration;
Environment = env;
}
public IConfiguration Configuration { get; }
public IHostEnvironment Environment { get; }
public void ConfigureServices(IServiceCollection services)
{
var useSso = AuthenticationMode.UseSingleSignOn(Configuration, Environment);
services.AddXafBlazor(...);
services.AddXafSecurity(o =>
{
o.RoleType = typeof(PermissionPolicyRole);
o.UserType = typeof(ApplicationUser);
})
.AddPasswordAuthentication(o => o.IsSupportChangePasswordPage = !useSso)
.ConfigureAuthentication(b =>
{
if (useSso) b.AddWindowsAuthentication();
});
if (Configuration.GetValue<bool>("Jobs:UseHangfire"))
{
services.AddHangfire(...);
services.AddHangfireServer();
}
}
}Always register password authentication, even in Production. The Hangfire service account needs it (see below). SSO is added on top via ConfigureAuthentication.
The HangfireJob Service-Account Exception
Background jobs have no Windows session, so SSO doesn't work for them. Carve out one specific username that's allowed to use password auth in Production:
public class HidePasswordLogonController : WindowController
{
public HidePasswordLogonController()
{
TargetWindowType = WindowType.Main;
}
protected override void OnFrameAssigned()
{
base.OnFrameAssigned();
var env = ServiceProvider.GetRequiredService<IHostEnvironment>();
var config = ServiceProvider.GetRequiredService<IConfiguration>();
if (!AuthenticationMode.UseSingleSignOn(config, env)) return;
Frame.GetController<LogonController>()
.AcceptAction.Executing += (s, e) =>
{
var logonParams = ((LogonController)((SimpleAction)s).Controller)
.GetLogonParameters() as AuthenticationStandardLogonParameters;
if (logonParams != null && logonParams.UserName != "HangfireJob")
{
throw new UserFriendlyException(
"Password sign-in is disabled. Use Windows Authentication.");
}
};
}
}Hangfire side authenticates HangfireJob via a direct SecurityStrategyBase.Logon call (no SignInManager because there's no Blazor circuit). The password lives at HangfireJob:Password in appsettings.{Environment}.json (read separately for each environment so dev can be blank).
public sealed class XafJobScopeInitializer(
IServiceProvider sp, ILogger<XafJobScopeInitializer> log) : IJobScopeInitializer
{
private const string ServiceUserName = "HangfireJob";
public Task InitializeAsync(CancellationToken ct = default)
{
var strategy = sp.GetRequiredService<ISecurityStrategyBase>();
if (strategy.IsAuthenticated) return Task.CompletedTask;
var nonSecured = sp.GetRequiredService<INonSecuredObjectSpaceFactory>();
var password = sp.GetService<IConfiguration>()?["HangfireJob:Password"] ?? "";
if (strategy is SecurityStrategy concrete)
concrete.Authentication.SetLogonParameters(
new AuthenticationStandardLogonParameters(ServiceUserName, password));
using var space = nonSecured.CreateNonSecuredObjectSpace<ApplicationUser>();
((SecurityStrategyBase)strategy).Logon(space);
return Task.CompletedTask;
}
}Notes:
SignInManager.SignIndoes not work in Hangfire worker threads — there is no Blazor circuit or HTTP context. UseSecurityStrategyBase.Logondirectly.HangfireJobmust exist in the database with the roles the jobs need (typically a custom "Service Account" role with broad type permissions but no UI navigation).- Do not commit the password to source. Use environment variables or a secret store;
appsettings.Production.jsonshould be deployed but excluded from git.
appsettings Layering
appsettings.json (base, shared defaults):
{
"Authentication": { "UseSingleSignOn": false },
"Jobs": { "UseHangfire": false },
"HangfireJob": { "Password": "" }
}appsettings.Production.json:
{
"Authentication": { "UseSingleSignOn": true },
"Jobs": { "UseHangfire": true }
}appsettings.Test.json:
{
"Authentication": { "UseSingleSignOn": false },
"Jobs": { "UseHangfire": true }
}appsettings.Development.json:
{
"Authentication": { "UseSingleSignOn": false },
"Jobs": { "UseHangfire": false }
}Verification Checklist
When auth misbehaves, check in this order:
- Environment:
Get-ChildItem Env:ASPNETCORE_ENVIRONMENTon the host (or the IIS site's env vars). The error is almost always here. - Which appsettings was loaded: log
env.EnvironmentNameandconfig["Authentication:UseSingleSignOn"]at startup. - AppPool identity (IIS): for SSO, the AppPool must run as an account that can read the user's AD token via Windows Auth — usually
ApplicationPoolIdentityis fine if IIS Windows Authentication is enabled. - IIS modules: Windows Authentication must be installed and enabled on the site; Anonymous must be disabled for SSO endpoints.
- Browser: SSO is browser-dependent. Chrome/Edge need the site in the Local Intranet zone (or an explicit allow policy) to send the Kerberos/NTLM token without prompting.
Common Mistake
Publishing as Debug does not force classic login anymore. The build configuration only affects compile-time optimizations; what decides auth is ASPNETCORE_ENVIRONMENT at startup. A Release build running with ASPNETCORE_ENVIRONMENT=Development will let users log in with passwords.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

