title: ASP.NET MVC LDAP Authentication
body: <p>I have been trying to authenticate via LDAP on a new application I'm developing in vain. I have always been able to do this on other applications but this time for some reason it just won't go through. I open my other apps and try to replicate the code almost identical but I keep running into the same problem. The app redirects to the page it should if the authentication was successful but when I try to navigate to another page where I have a function with <code>[Authorize]</code> before it, it take's me back to the log in page. I have tried in vain to check what the issue could be but I still can't find it. Please assist. Here's some portions of my code</p>
  
  <pre><code>//Accounts controller
  [HttpPost]
  public ActionResult Login(LoginViewModel model, string returnUrl)
  {
  
      string domain = (string)model.domain   
      string userName = (string)model.UserName;
      string password = (string)model.Password;
  
      try
      {
          DirectoryEntry entry = new DirectoryEntry();
          switch (domain)
          {
              case "OPTION1":
                  entry = new DirectoryEntry("LDAP://xx.xx.xx.xx:389", userName, password);
                  break;
              case "OPTION2":
                  entry = new DirectoryEntry("LDAP://yy.yy.yy.yy:389", userName, password);
                  break;
  
          }
          object nativeObject = entry.NativeObject;
          FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
          if (this.Url.IsLocalUrl(returnUrl) &amp;&amp; returnUrl.Length &gt; 1 &amp;&amp; returnUrl.StartsWith("/")
                      &amp;&amp; !returnUrl.StartsWith("//") &amp;&amp; !returnUrl.StartsWith("/\\"))
          {
              return this.Redirect(returnUrl);
          }
          return this.RedirectToAction("Index", "Home");
  
  
      }
      catch (Exception ex)
      {
  
          this.ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");
      }
      return View(model);
  }
  
  //web.config
  &lt;authentication mode="Forms"&gt;
    &lt;forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="60" slidingExpiration="false" protection="All" /&gt;
  &lt;/authentication&gt;
  
  
  //in AccountViewModels I have
  using System.ComponentModel.DataAnnotations;
  
  public class LoginViewModel
  {
  [Required]
  [Display(Name = "User name")]
  public string UserName { get; set; }
  
  [Required]
  [DataType(DataType.Password)]
  [Display(Name = "Password")]
  public string Password { get; set; }
  
  [Display(Name = "Remember me?")]
  public bool RememberMe { get; set; }
  }
  </code></pre>