【发布时间】:2022-01-25 15:27:03
【问题描述】:
我对这段简单的代码有疑问:
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);
}
}
当我在Visual Studio 中通过IIS Express 启动我的asp net 应用程序时,一切正常。我在这种情况下的日志:
2021-12-25 22:02:53.1783 TRACE windows user `Domain\username` is trying to access the system.
但userName 在远程 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.
我正在尝试从本地主机和通过域名打开网站,也将其添加到受信任的站点中,但没有任何帮助。
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>
在 IIS 上启用匿名身份验证
因为如果没有,我连error/unauthorized这样的页面都打不开:
【问题讨论】:
-
无法启用匿名身份验证。
-
@user9938 我不使用数据库。管理员名称存储在 json 配置中。但问题是
userName变量为空。 -
@LexLi 否则我无法打开任何页面。请查看最后一个屏幕。
-
如果我解释所有关于 Windows 身份验证的内容将会很冗长,所以除了一些关键的事情我不会说。 1)如果你想使用它,那么需要相当多的设置docs.microsoft.com/en-us/aspnet/core/security/authentication/… 2)你的ASP.NET Core代码也必须相应地改变。 3) 如果您的浏览器不发送凭据,则可能会出现 401 错误。如何排除故障是您可以从现有线程中学到的另一个重要主题。
-
不确定我是否理解如何更改我的代码,无论如何感谢 1) 和 2) 选项。关于 №3) - 我在 Internet Explorer 浏览器中将站点添加到受信任站点中,所以我认为问题不在浏览器中
标签: c# asp.net asp.net-core authentication iis