简体   繁体   中英

Authentication using active directory in asp.net MVC

I want to authenticate users in my asp.net mvc project using active directory, after hours and hours spent surfing on the internet i didn't find anything useful for me, I've already saw all the result but nothing.

I tryed to edit my web.config as many post suggests.

If anyone can help me with pieces of code or example i'll appreciate it a lot, because i have no idea where i can start from.

EDIT

My current web.config

<system.web>
<authentication mode="Forms">
  <forms name=".ADAuthCookie" loginUrl="~/MainMenu/Login" timeout="45" 
 slidingExpiration="false" protection="All" />
</authentication>
<authorization>
  <deny users="?" />
</authorization>
<membership defaultProvider="ADMembershipProvider">
  <providers>
    <clear />
     <add name="ADMembershipProvider" 
     type="System.Web.Security.ActiveDirectoryMembershipProvider"  
     connectionStringName="ADConnectionString" 
     attributeMapUsername="sAMAccountName" />
  </providers>
</membership>
</system.web>      
<connectionStrings>
 <add name="ADConnectionString" 
   connectioString="LDAP://myserver.mydomain.COM:389/DC=mydomain,DC=COM" />
</connectionStrings>

Leo

I solved my problem setting view model and controller like this:

Model

public class LogOnModel
{
    [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; }
}

Controller

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

    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Main", "MainMenu");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect");
            }
        }

        // if we got this far, something failed, redisplay form
        return View(model);
    }

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

        return RedirectToAction("Login", "Account");
    }

View

<body id="bodyMain">
@using (Html.BeginForm("LogOn", null,FormMethod.Post))
{
<div class="container">
    @Html.ValidationSummary(true, "")
    <div style="padding-top:30%"></div>
    <table>
        <tr>
            <td>@Html.EditorFor(model => model.UserName)</td>
            <td>@Html.ValidationMessageFor(model => model.UserName, "",)</td>
        </tr>
        <tr></tr>
        <tr>
            <td>@Html.EditorFor(model => model.Password)</td>
            <td>@Html.ValidationMessageFor(model => model.Password, "")</td>
        </tr>
        <tr>
            <td>@Html.CheckBoxFor(model=>model.RememberMe)</td>               
        </tr>
    </table>
    <br />
    <button type="submit" class="btn btn-info">Login</button>
</div>
}

And the web.config remain the same as my question

As mentioned in the comments, it's as easy as changing your authentication method from Forms to Windows :

<authentication mode="Windows" />

That will work if the server you run this from is joined to the same domain as your users are logging in to, or a trusted domain. Users will not be prompted to login, as long as your site is setup as a trusted site (Intranet sites usually are).

To restrict parts of your application, you can use AuthorizeAttribute . For example, to restrict access to those in an AD group:

[Authorize(Roles="DOMAIN\GroupName")]

or, to restrict access to a specific AD user:

[Authorize(Users="DOMAIN\UserName")]

Multiple roles or users can be added by separating with a comma:

[Authorize(Roles="DOMAIN\Group1, DOMAIN\Group2")]

Those attributes can be applied to a whole controller, or to individual actions.

More information here .

If you need to Authenticate איק username and Password submitted by a user against AD, use the below code.

Add reference to System.DirectoryServices.AccountManagement

and in the code file

using System.DirectoryServices.AccountManagement;

Next, in your POST Method(flag is boolean type variable)

PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DOMAINNAME");
            flag = pc.ValidateCredentials(UserName, Password);

If the flag is true, then credentials are valid otherwise they are not.

In this case, you need to manually set up the USER and roles (by using forms authentication), then you may restrict user/roles to display controller/views by using

[Authorize(Roles="RoleName")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM