Sta*_*ace 21 c# vb.net asp.net security windows-identity
我有一个使用ASP.NET表单身份验证的ASP.NET 3.5应用程序.我希望能够在页面中编辑数据时获取当前登录到计算机的Windows用户名(不登录到ASP.NET应用程序,但登录到Windows).
如果我使用Context.User.Identity.Name.Tostring(),我会将用户名登录到ASP.NET应用程序中,但我需要Windows帐户名.
System.Security.Principal.WindowsIdentity.GetCurrent().Name.Tostring()
Run Code Online (Sandbox Code Playgroud)
此外,它仅在我从Visual Studio运行网站时有效,但在部署到IIS后,它返回NT AUTHORITY\SYSTEM.
小智 10
要将当前登录的用户转换为Windows帐户,您必须使用Windows authentication而不是Forms authentication:
System.Security.Principal.WindowsIdentity.GetCurrent().Name.Tostring()也只有在我从visual studio运行网站时才有效,但在部署到IIS后它返回NT AUTHORITY\SYSTEM
它显示了应用程序当前用户.在Visual Studio Web服务器上托管应用程序时,它使用您的本地帐户.但是,当您使用不同凭据登录Web应用程序时,它将始终显示您当前的Windows登录名.
部署到IIS的应用程序在您的情况下使用NT AUTHORITY\SYSTEM帐户.
小智 9
要使用C#将当前登录的用户导入Windows,请使用:
string Username = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
Run Code Online (Sandbox Code Playgroud)
小智 7
我努力奋斗,奋力拼搏.其中一件事是我无法访问被锁定的IIS,因此我无法更改任何服务器设置.我不得不在代码中使用我能做的事情.当我研究它时,许多回复说,"设置这样的IIS"...well,当你有权访问IIS时,这很棒,但我没有 - 我必须使用我在代码中可以做的事情.所以,我最终像这样处理它:
在我的Web配置文件中,我在该部分中添加了以下代码行:
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="false" />
<windowsAuthentication enabled="true" />
</authentication>
</security>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
然后,它在我的本地返回了一个错误,我必须进入并修复.我去了我的机器上以下路径中的applicationhost.config文件(你的可能不同):
C:\ users \"您的用户名"\ My Documents \"yourIISInstallation"\ config\applicationhost.config
我将以下设置更改为"允许",已将其设置为"拒绝":
<section name="anonymousAuthentication" overrideModeDefault="Deny" />
Run Code Online (Sandbox Code Playgroud)
变成
<section name="anonymousAuthentication" overrideModeDefault="Allow" />
Run Code Online (Sandbox Code Playgroud)
和
<section name="windowsAuthentication" overrideModeDefault="Deny" />
Run Code Online (Sandbox Code Playgroud)
至
<section name="windowsAuthentication" overrideModeDefault="Allow" />
Run Code Online (Sandbox Code Playgroud)
在里面
<sectionGroup name="authentication">
Run Code Online (Sandbox Code Playgroud)
部分.在我发现这个问题之前,我正在把头发拉出来.我希望这可以帮助别人.一旦我将上面的代码放入webconfig文件,它就在Intranet上工作,它只是在我的本地返回错误,但是一旦我将上面的内容添加到我的本地applicationhost.config文件中,它就开始在我的本地工作了同样.然后,我调用以下变量来返回Windows上登录用户的名称:
HttpContext.Current.User.Identity.Name.ToString().Substring((HttpContext.Current.User.Identity.Name.ToString().IndexOf("\\")) + 1);
Run Code Online (Sandbox Code Playgroud)
干杯!