7

I already have a website written using MVC 5 and it uses form authentication using SQL Server.

Now is it possible that I can bypass Forms Authentication for users that are already on office network. Also I want to keep track of user and apply rules similar to Forms Authentication. Thanks.

Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
ary
  • 939
  • 2
  • 13
  • 32

1 Answers1

1

Yes you can do that. Here's the code to check user in domain. First get the domain name and try to verify user with domain. If this fails then proceed to forms authentication.

 public static string DomainControllerName { get; private set; }
 public static string ComputerName { get; private set; }
 public static string DomainName { get; private set; }
 public static string DomainPath
 {
            get
            {
                bool bFirst = true;
                StringBuilder sbReturn = new StringBuilder(200);
                string[] strlstDc = DomainName.Split('.');
                foreach (string strDc in strlstDc)
                {
                    if (bFirst)
                    {
                        sbReturn.Append("DC=");
                        bFirst = false;
                    }
                    else
                        sbReturn.Append(",DC=");

                    sbReturn.Append(strDc);
                }
                return sbReturn.ToString();
            }
 }
        public static string RootPath
        {
            get
            {
                return string.Format("LDAP://{0}/{1}", DomainName, DomainPath);
            }
        }
Domain domain = null;
DomainController domainController = null;
try
{
    domain = Domain.GetCurrentDomain();
        DomainName = domain.Name;
        domainController = domain.PdcRoleOwner;
        DomainControllerName = domainController.Name.Split('.')[0];
        ComputerName = Environment.MachineName;
}
finally
{
if (domain != null)
       domain.Dispose();
if (domainController != null)
       domainController.Dispose();
}


try
{
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
    {
                DirectoryEntry root = new DirectoryEntry(RootPath, txtUserName.Text.Trim(), txtPassword.Text);
                DirectorySearcher search = new DirectorySearcher(root);

            search.SearchScope = SearchScope.Subtree;
            search.Filter = "(sAMAccountName=" + txtUserName.Text.Trim() + ")";
            SearchResultCollection results = search.FindAll();

            UserPrincipal userP = UserPrincipal.FindByIdentity(ctx, txtUserName.Text.Trim());

            if (userP != null && results != null)
            {
                //Get the user's groups
                var groups = userP.GetAuthorizationGroups();
                if (groups.Count(x => x.Name == ConfigurationManager.AppSettings["UserGroup"].ToString()) > 0)
                {
                    //Successful login code here
                }
                else
                {
                    //"Access Denied !";
                }
            }
            else
            {
                //"User Name or Password is incorrect. Try again !"
            }
        }
    }
    catch
    {
        //"User Name or Password is incorrect. Try again !"
    }
Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
  • Thanks so much @Rahul. Can you please tell me where shall I put this code. Sorry I am very new to asp.net and MVC. – ary Dec 14 '15 at 05:53
  • You should use this code before your `Forms Authentication` code logic. – Rahul Nikate Dec 14 '15 at 05:56
  • So @Rahul if I create a simple MVC 5 application using "Individual User Accounts" template, then will it go in AccountController Login method ? – ary Dec 14 '15 at 06:05
  • Thanks again @Rahul. I will give this try. Looks complicated for me :) So is that function validating using AD username and password. I was thinking that MVC should automatically detect if user is already on network or not. A request-> Is it possible that you can have a simple project with above features posted on github. I am sure others will benefit too. – ary Dec 14 '15 at 06:46
  • I do not have sample project for this. But you can add your doubts here, I'll answer it – Rahul Nikate Dec 14 '15 at 07:11
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/97823/discussion-between-ary-and-rahul-nikate). – ary Dec 14 '15 at 07:39