2016-04-19 533 views
1

我一直在嘗試通過LDAP對我正在開發的新應用程序進行身份驗證。我一直可以在其他應用程序上做到這一點,但這次出於某種原因,它只是不會通過。我打開其他應用程序並嘗試複製幾乎完全相同的代碼,但我一直遇到同樣的問題。如果身份驗證成功,應用程序會重定向到它應該訪問的頁面,但是當我嘗試導航到另一個頁面時,如果在它之前有[Authorize]的功能,它會將我帶回登錄頁面。我曾徒勞地試圖檢查問題可能是什麼,但我仍然無法找到它。請協助。這裏是我的代碼的一些部分ASP.NET MVC LDAP身份驗證

//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) && returnUrl.Length > 1 && returnUrl.StartsWith("/") 
        && !returnUrl.StartsWith("//") && !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 
<authentication mode="Forms"> 
    <forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="60" slidingExpiration="false" protection="All" /> 
</authentication> 


//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; } 
} 

回答

0

我在這裏可以看到的問題是你沒有驗證用戶。 例如

if (Membership.ValidateUser(model.UserName, model.Password)) 
{ 
    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 
    if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 &&  returnUrl.StartsWith("/") 
      && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) 
     { 
      return this.Redirect(returnUrl); 
     } 

     return this.RedirectToAction("Index", "Home"); 
}