[英]Active Directory Authentication with Retrieving User Data in MVC
In my MVC5 application, I used to apply the following approach by just checking if the user is exist or not in Active Directory
. 在我的MVC5应用程序中,我过去仅通过检查用户是否存在于
Active Directory
来应用以下方法。 Now, I want to use another approach like that: I send the username
and password
to the active directory
and if the user exists in it, it should return some active directory
info ie user's Name
, Surname
, Department
. 现在,我想使用另一种方法:将
username
和password
发送到active directory
,如果用户存在,则它应该返回一些active directory
信息,即用户的Name
, Surname
, Department
。 So, how can I define such a kind of authentication in Controller
and web.config
? 因此,如何在
Controller
和web.config
定义这种身份验证?
web.config : 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="myadmin@company" connectionPassword="MyPassword" />
</providers>
</membership>
</system.web>
<connectionStrings>
<!-- for LDAP -->
<add name="ADConnectionString" connectionString="LDAP://adadfaf.my.company:111/DC=my,DC=company" />
</connectionStrings>
</configuration>
Controller: 控制器:
[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);
}
What I did was to create a Class "Session User" which where holding the UserID, LoginName and were able to Validate the User Credentials. 我所做的是创建一个“会话用户”类,其中包含UserID,LoginName并能够验证用户凭据。
In this Class you also got to put/call the Methods/Properties to get department, Surname and more... 在本课程中,您还必须放置/调用方法/属性以获取部门,姓氏等等。
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;
}
}
The next step was to create a Controller, in my case "AccountController" which handels the Login and Logout of an user. 下一步是创建一个控制器,在我的例子中是“ AccountController”,它可以处理用户的登录和注销。 It uses FormsAuthentication to set auth.
它使用FormsAuthentication设置身份验证。 cookies.
饼干。
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);
}
}
}
The Last step is to configure the conf. 最后一步是配置conf。 file to use the auth.
文件以使用身份验证。 mode Forms
模式表格
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="1440" /> <!--1440min = 24hours-->
</authentication>
Now you just have to call Login in the view and pass the parameters and you are good. 现在,您只需要在视图中调用Login并传递参数即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.