I have a problem with this simple piece of code:
public void OnAuthorization(AuthorizationFilterContext context)
{
ClaimsPrincipal user = _httpContextAccessor.HttpContext.User;
ClaimsIdentity identity = user.Identity as ClaimsIdentity;
string userName = identity.Name; //!!!
_logger.Trace("windows user `{0}` is trying to access the system", userName);
var admins = _configurationRoot.GetSection(ConfigDescription.Admins).Get<List<string>>();
if (!admins.Contains(userName))
{
_logger.Trace("Permission denied.");
context.Result = new RedirectResult("/error/unauthorized", false);
}
}
When I launch my asp net
app via IIS Express
in Visual Studio
everything works fine. My logs in this case:
2021-12-25 22:02:53.1783 TRACE windows user `Domain\username` is trying to access the system.
But userName
is always empty after publishing on remote IIS.
2021-12-25 19:11:55.2524 TRACE windows user `` is trying to access the system.
2021-12-25 19:11:55.2524 TRACE Permission denied.
I was trying open website from localhost and via domain name, also added it into Trusted Sites, nothing helped.
web.config
:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" forwardWindowsAuthToken="true" arguments=".\BlaBla.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
Anonymous Authentication is enabled on IIS
Because if not, I can't open even error/unauthorized
page like this:
CodePudding user response:
To enable windows authentication in IIS need to make sure the followings
- Enable Windows Authentication in IIS
- Enable Windows Authentication in IIS web application
1. Enable Windows Authentication in IIS
we need to enable Windows Authentication in “Windows features” (Run command : optionalfeatures . Win R → optionalfeatures)
2. Enable Windows Authentication in IIS web application
Then we need to Enable windows authentication for applications. Can be done in web.config as below or in IIS
web.config
<system.webServer>
<security>
<authentication>
<windowsAuthentication enabled="true" />
<anonymousAuthentication enabled="false" />
</authentication>
</security>
</system.webServer>
IIS
Select the application in left node and select "Authentication" in feature view
Enable Windows Authentication and Disable anonymous Authentication.
More information