MVC 5 Authentication Workarounds for Authenticated Windows Users

I already have a site written using MVC 5 , and it uses authentication using SQL Server .

Now it’s possible that I can bypass Forms Authentication for users who are already on the office network. I also want to track the user and apply rules similar to Forms Authentication . Thanks.

+7
c # asp.net-mvc-5 form-authentication windows-authentication
source share
1 answer

Yes you can do it. Here is the code to verify the user in the domain. First get the domain name and try checking the user with the domain. If this fails, go to 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 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 !" } 
+1
source share

All Articles