【问题标题】:Force windows authentication and allow anonymous强制 Windows 身份验证并允许匿名
【发布时间】:2023-04-09 02:16:02
【问题描述】:

我的想法是让我的家人使用他们的 Windows 用户名进入应用程序(这样他们就不必编写它),并使用 Identity 将密码和其他内容保存到本地 MDF 数据库中。问题是我无法弄清楚如何强制 Windows 身份验证(以便Context.User.Identity.Name 为我提供 Windows 用户名)并使用该信息登录身份数据库。为了创建项目,我使用了个人帐户作为安全类型的 Web 表单模板,并删除了所有 Owin 第三方登录包(Microsoft、Google 等)。
这是我尝试过的:

Default.aspx.cs(我的需要身份验证的主页)

protected void Page_Load(object sender, EventArgs e)
{
    //According to Identity comments, ApplicationCookie is the AuthenticationType...
    //once logged in through Identity
    if (Context.User.Identity.AuthenticationType != "ApplicationCookie")
        Response.Redirect("Login.aspx", true);
}

Login.aspx.cs

protected void LogIn(object sender, EventArgs e) //login button handler
{
    var manager = Context.GetOwinContext().GetUserManager<UserAdministrator>();
    var signinManager = Context.GetOwinContext().GetUserManager<SessionAdministrator>();

    string windowsName = Context.User.Identity.Name;
    User user = manager.Users.Where(u => u.UserName == windowsName).FirstOrDefault();
    // rest of the login code...
}

web.config(全局)

<location path="Login.aspx"> //this should only allow windows logged-in users
  <system.web>
      <authorization>
        <allow users="*" />
        <deny users="?" />
     </authorization>
  </system.web>
</location>
<location path="default.aspx"> // this should only allow Identity-logged in users
  <system.web>
    <authorization>
      <allow users="*" />
      <deny users="?" />
    </authorization>
  </system.web>
</location>

项目属性

  • Windows 身份验证设置为启用
  • 匿名身份验证设置为禁用

由于某种原因,启动应用程序并浏览到 default.aspx 或 login.aspx,不使用 Windows 身份验证,因此Context.User.Identity.IsAuthenticated 返回 false。我怎样才能实现我想要的?

【问题讨论】:

  • 您的应用程序是否托管在 IIS 或 IISExpress 中?
  • @Mitklantekutli 直接通过 Visual Studio 2013 (IISExpress) 调试

标签: c# asp.net authentication webforms


【解决方案1】:

尝试在 default.aspx 节点中删除 &lt;allow users="*" /&gt;

它将通过拒绝匿名来强制应用使用身份验证

【讨论】:

  • 由于某种原因,我被自动重定向到 Login.aspx(我不记得我是怎么做到的),但重定向一直持续到我得到“查询字符串太长”
【解决方案2】:

这算是解决了。

我删除了 Windows 身份验证并切换到 Forms 身份验证,并使用我找到的此代码获取 Windows 用户名(不记得是谁用它回答了 SO 问题):

System.Security.Principal.WindowsPrincipal windowsUser = new System.Security.Principal.WindowsPrincipal(Request.LogonUserIdentity);
Request.LogonUserIdentity.Impersonate();
string username = windowsUser.Identity.Name.Substring(windowsUser.Identity.Name.LastIndexOf("\\") + 1);

【讨论】:

    猜你喜欢
    • 2018-04-30
    • 2011-04-16
    • 2021-03-23
    • 2011-05-14
    • 2015-02-09
    • 2019-09-16
    • 1970-01-01
    • 2019-01-09
    • 2020-12-21
    相关资源
    最近更新 更多