如何在 Razor (cshtml) 中进行 Active Directory 身份验证 [英] How to do Active Directory authentication in Razor (cshtml)

查看:32
本文介绍了如何在 Razor (cshtml) 中进行 Active Directory 身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Razor 做一个简单的网站.目前,我有基于数据库的身份验证,如下所示:

I am doing a simple website with Razor. Currently, I have database-based authentication that works, as follows:

在_AppStart.chtml中:

In _AppStart.chtml:

WebSecurity.InitializeDatabaseConnection("db_connection",
       "users", "id", "username", true);

在 login.cshtml 页面中:

In login.cshtml page:

    username = Request["username"];
    password = Request["password"];

    if (WebSecurity.Login(username, password, true))
    {
        Response.Redirect("/admin");
    }
    else
    {
        errorMessage = "Login was not successful.";
    }

在受保护的 CSHTML 页面中,我在页面顶部有以下内容:

In protected CSHTML pages, I have the following at the top of a page:

if (!WebSecurity.IsAuthenticated)
{
    Response.Redirect("/login.cshtml");
}

一切都非常简单并且运行良好.现在我想用 AD 添加身份验证.我不知道该怎么做.

Everything is pretty simple and works well. Now I would like to add authentication with AD. I don't know how to do it.

我来自 Java 世界,拥有多年的经验.对于这个简单的网站,我不需要 MVC 架构.我需要类似于上面的简单东西(如果可能的话).我需要在 login.cshtml 文件中进行身份验证.我用谷歌搜索了很多,但找不到我需要的教程(以便我可以复制和粘贴).

I came from the Java world with many years of experience. For this simple website, I do not need MVC architecture. I need simple things similar to the above (if possible). I need to do authentication just within the login.cshtml file. I googled a lot and am unable to find a tutorial (so that I can copy and paste) for what I need.

非常感谢任何指针或帮助!

Any pointers or help is really appreciated!

感谢和问候

更新:此应用程序位于内部网络上.

更新2:这是我成功实现X3074861X的代码后的代码

if (IsPost)
{
    username = Request["username"];
    password = Request["password"];
    var domain = "domain";
    var host = "host";
    var port = "389";

    LdapConnection ldapConnection = new LdapConnection(host + ":" + port);
    try
    {
        // authenticate the username and password
        using (ldapConnection)
        {
            // pass in the network creds, and the domain.
            var networkCredential = new NetworkCredential(username, password, domain);
            // if we're using unsecured port 389, set to false. If using port 636, set this to true.
            ldapConnection.SessionOptions.SecureSocketLayer = false;
            // since this is an internal application, just accept the certificate either way
            ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
            // to force NTLMKerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
            ldapConnection.AuthType = AuthType.Basic;
            // this is where the authentication occurs
            ldapConnection.Bind(networkCredential);

            //check local database to make sure the user is one of we allowed
            if (WebSecurity.Login(username, "fixed-password, just to check whether someone is on the list of allowed people", true))
            {
                Response.Redirect("/admin");
            }
            else
            {
                errorMessage = "Login was not successful.";
            }
        }
    }

    catch (LdapException exception)
    {
        //Authentication failed, exception will dictate why
        errorMessage = "Login was not successful.";
    }

一些解释.我无法控制 AD,因此我只能针对它对用户进行身份验证.我仍然有一个小的本地数据库,指示谁可以访问该应用程序.有权访问该应用的每个人都拥有相同的权利.

Some explanation. I dont have control over the AD and so I can only authenticate users against it. I still have a little local database that indicates who can access the app. Everyone with access to the app has the same rights.

感谢 X3074861X.

推荐答案

由于这是一个内部应用程序,并且您正在寻找简单的东西,我会考虑编写一个类来执行 Active Directory 身份验证.不过,您需要做几件事才能使其正常工作:

Since this is an internal application, and you're looking for something simple, I would consider writing a single class to do the Active Directory authentication. You're going to need a couple things though, in order for this to work :

  • 在您的项目中对 System.DirectoryServices.Protocols 的引用.
  • 您的 Active Directory 服务器的 IP 或 DNS 名称.我们将在下面的代码中将其称为 host.
  • 运行它的端口(LDAPS 将是端口 636,基本 LDAP 将是端口 389).我们将在下面的代码中将其称为 port.
  • 您的用户所属的域.我们将在下面的代码中将其称为 domain.
  • A reference to System.DirectoryServices.Protocols in your project.
  • The IP or DNS name of your Active Directory server. We'll call it host in the code below.
  • The port it's running on (LDAPS will be port 636, basic LDAP will be port 389). We'll call it port in the code below.
  • The Domain to which your users belong. We'll call it domain in the code below.

现在您已经有了它,您可以将其连接起来,以根据您的 AD 实例检查请求中的凭据.我会尝试这样的事情:

Now that you have that, you can wire this up to check the credentials from the request against your AD instance. I would try something like this :

// the username and password to authenticate
username = Request["username"];
password = Request["password"];

// define your connection
LdapConnection ldapConnection = new LdapConnection("host:port");

try
{
      // authenticate the username and password
      using (ldapConnection)
      {
          // pass in the network creds, and the domain.
          var networkCredential = new NetworkCredential(username, password, domain);

          // if we're using unsecured port 389, set to false. If using port 636, set this to true.
          ldapConnection.SessionOptions.SecureSocketLayer = false;

          // since this is an internal application, just accept the certificate either way
          ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };

          // to force NTLMKerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
          ldapConnection.AuthType = AuthType.Basic;

          // authenticate the user
          ldapConnection.Bind(networkCredential);
      }
      catch (LdapException ldapException)
      {
          //Authentication failed, exception will dictate why
      }
}

此外,与您之前传达授权问题的方式相同,ldapException 可以告诉您调用失败的原因.如果您想显示自定义消息,我会检查 LdapException.ErrorCode 属性,并可能创建基于 错误代码.

Also, in the same way you'd communicate an authorization issue before, the ldapException can tell you why the call failed. If you want to display custom messaging, I would check the LdapException.ErrorCode property, and maybe create a case statement of return messages based on the error codes.

或者,您可以直接将 LdapException.Message 输出到页面 - 无论哪种方式,这至少会告诉用户为什么他们的登录不起作用.

Or, you could just output LdapException.Message directly to the page - either way, that will at least dictate to the user why their login didn't work.

这篇关于如何在 Razor (cshtml) 中进行 Active Directory 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆