0

В моем приложении MVC5 я использовал следующий подход, просто проверяя, существует ли пользователь в Active Directory. Теперь я хочу использовать другой подход вроде: Я посылаю username и password к active directory и если пользователь существует в нем, он должен возвращать некоторые active directory данные пользователя, т.е. Name, Surname, Department. Итак, как я могу определить такую ​​аутентификацию в Controller и web.config?Аутентификация Active Directory с получением данных пользователя в MVC

web.config:

<configuration> 
    <system.web> 
    <httpCookies httpOnlyCookies="true" /> 
    <authentication mode="Forms"> 
     <forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="45" slidingExpiration="false" protection="All" /> 
    </authentication> 
    <membership defaultProvider="ADMembershipProvider"> 
     <providers> 
     <clear /> 
     <add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" connectionUsername="[email protected]" connectionPassword="MyPassword" /> 
     </providers> 
    </membership> 
    </system.web> 
    <connectionStrings> 
    <!-- for LDAP --> 
    <add name="ADConnectionString" connectionString="LDAP://adadfaf.my.company:111/DC=my,DC=company" /> 
    </connectionStrings> 
</configuration> 


Контроллер:

[AllowAnonymous] 
[ValidateAntiForgeryToken] 
[HttpPost] 
public ActionResult Login(User model, string returnUrl) 
{ 
    if (!this.ModelState.IsValid) 
    { 
     return this.View(model); 
    }  

    //At here I need to retrieve some user data from Active Directory instead of hust a boolean result 
    if (Membership.ValidateUser(model.UserName, model.Password)) 
    { 
     //On the other hand I am not sure if this cookie lines are enough or not. Should I add some additional lines? 
     FormsAuthentication.SetAuthCookie(model.UserName, false); 
     if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") 
      && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) 
     { 
      return this.Redirect(returnUrl); 
     } 
     return this.RedirectToAction("Index", "Issue"); 
    } 

    TempData["message"] = "The user name or password provided is incorrect."; 
    return this.View(model); 
} 

ответ

0

Что я сделал, чтобы создать класс "Сеанс пользователя", который где удерживающий UserID , LoginName и смогли проверить учетные данные пользователя.

В этом классе вы также должны положить/вызывать методы/Свойства, чтобы получить отдел, Фамилия и больше ...

public class SesssionUser 
{ 
    [Key] 
    [Required] 
    public int UserId { get; set; } 
    [Required] 
    public string LoginName { get; set; } 
    [Required] 
    [DataType(DataType.Password)] 
    public string Password { get; set; } 


    private Boolean IsAuth{ get; set; } 
    public string Department 
    { 
     get { 
     return GetDepartment(); 
     } 
    } 

    private string GetDepartment() 
    { 
     if(!IsAuth) { return null; } 
     //Gets the department. 
    } 

    private bool Authenticate(string userName,string password, string domain) 
    { 
     bool authentic = false; 
     try 
     { 
      DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, 
      userName, password); 
      object nativeObject = entry.NativeObject; 
      authentic = true; 
     } 
      catch (DirectoryServicesCOMException) { } 
      return authentic; 
    } 

    /// <summary> 
    /// Validates the user in the AD 
    /// </summary> 
    /// <returns>true if the credentials are correct else false</returns> 
    public Boolean ValidateUser() 
    { 
     IsAuth = Authenticate(LoginName,Password,"<YourDomain>"); 
     return IsAuth; 
    } 
} 

Следующим шагом было создание контроллера, в моем случае «AccountController» который переносит вход и выход пользователя. Он использует FormsAuthentication для установки auth. печенье.

using System; 
using System.Globalization; 
using System.Linq; 
using System.Security.Claims; 
using System.Threading.Tasks; 
using System.Web; 
using System.Web.Mvc; 
using Microsoft.AspNet.Identity; 
using Microsoft.AspNet.Identity.Owin; 
using Microsoft.Owin.Security; 
using System.Web.Security; 

using MVCErrorLog.Models; 

//My class 
using Admin.ActiveDirectoryHelper.Objects; 

using MVCErrorLog.ViewModels; 

namespace MVCErrorLog.Controllers 
{ 

    public class AccountController : Controller 
    { 
     public ActionResult Login() 
     { 
      return View(); 
     } 

     [HttpPost] 
     [ValidateAntiForgeryToken] 
     public ActionResult Login(string username, string pw) 
     { 
      if (!ModelState.IsValid) { return RedirectToAction("Index", "Home"); } 

      var sessionUser = new SesssionUser(); 
      sessionUser.LoginName = username; 
      sessionUser.Password = pw; 
      sessionUser.UserId = 1; 

      if (!sessionUser.ValidateUser()) { return View("Login"); } 
      FormsAuthentication.SetAuthCookie(sessionUser.LoginName, true); 
      return RedirectToAction("Index", "ErrorLogs"); 
     } 

     public ActionResult LogOff() 
     { 
      FormsAuthentication.SignOut(); 

      return RedirectToAction("Index", "ErrorLogs"); 
     } 


     private SesssionUser SetupFormsAuthTicket(SesssionUser user, bool persistanceFlag) 
     { 
      var userData = user.UserId.ToString(CultureInfo.InvariantCulture); 
      var authTicket = new FormsAuthenticationTicket(1, //version 
           user.LoginName, // user name 
           DateTime.Now,    //creation 
           DateTime.Now.AddMinutes(30), //Expiration 
           persistanceFlag, //Persistent 
           userData); 

      var encTicket = FormsAuthentication.Encrypt(authTicket); 
      Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); 
      return user; 
     } 


     protected override void Dispose(bool disposing) 
     { 
      if (disposing) 
      { 

      } 

      base.Dispose(disposing); 
     } 
    } 
} 

Последний шаг - настроить конфиг. файл для использования auth. Режим форм

<authentication mode="Forms"> 
    <forms loginUrl="~/Account/Login" timeout="1440" /> <!--1440min = 24hours--> 
</authentication> 

Теперь вы просто должны позвонить войти в представлении и передать параметры, и вы хорошо.

+0

Большое спасибо за ваш ответ. Я попытался применить это, но столкнулся с некоторыми проблемами, то есть «Имя« SearchPattern »не существует в текущем контексте» в классе SesssionUser. С другой стороны, CurrUser = false; линия не должна работать. Должны ли мы присваивать значение null вместо false? Поскольку Пользователь не является логическим типом и является классом домена. –

+0

Thats класс, который я создал для моего компаньона, также класс 'User'. Мне не разрешено записывать его в стек. В методе 'ValidateUser()' вы должны поместить свою собственную проверку для пользователя против AD. Вы можете взглянуть на [codeproject] (http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C) – C0d1ngJammer

+0

Я изменил код. Как я уже сказал, вам нужно создать свой собственный AD-Class, чтобы получить компанию, фамилию ... – C0d1ngJammer