MVC 4自动填充windows用户名

时间:2017-07-19 08:03:48

标签: asp.net windows asp.net-mvc-4 authentication

我正在ASP.NET MVC 4中使用混合身份验证模式,我希望在我的文本框中自动填充Windows用户名。我使用了System.Security.Principal.WindowsIdentity.GetCurrent().Name;并且它在本地工作正常,但是当我在服务器上执行它时,“Default AppPool”将出现在用户名文本框中。

我的cshtml代码 -

@model TMVCRepository.Models.ActivedirectoryModels
  @{
    ViewBag.Title = "Active directory authentication";

  }
 @{

     string UserIDwindows = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

    string[] Usernameis = UserIDwindows.Split('\\');


    if (ViewData["Error"] != "" && ViewData["Error"] != null)
    {
        string res = ViewData["Error"].ToString();

    <span style="color: red; font-size: 14px;">

        @res
    </span>

        ViewData["Error"] = null;



    }


}

@using (Html.BeginForm("index", "Activedirectory"))
{ 


    <h2>ENTER YOUR NETWORK / SYSTEM LOGIN CREDENTIALS


    </h2>


    <table width="100%">

        <tr>

            <td>

                @Html.LabelFor(a => a.UserID)

            </td>

        </tr>

        <tr>

            <td>

                @Html.TextBoxFor(a => a.UserID, new { @Value = Usernameis[1] })
                @*   @Html.TextBox(UserID,)*@

                @Html.ValidationMessageFor(a => a.UserID)

            </td>

        </tr>

        <tr>

            <td>

                @Html.LabelFor(a => a.Password)

            </td>

        </tr>

        <tr>

            <td>

                @Html.TextBoxFor(a => a.Password)

                @Html.ValidationMessageFor(a => a.Password)

            </td>

        </tr>

        <tr>

            <td>

                @Html.LabelFor(a => a.DomainName)

            </td>

        </tr>

        <tr>

            <td>

                @Html.TextBoxFor(a => a.DomainName)

                @Html.ValidationMessageFor(a => a.DomainName)

            </td>

        </tr>


        <tr>

            <td colspan="2">

                <input id="Submit1" type="submit" value="submit" />



            </td>

        </tr>

    </table>   

}

    my controller.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using TMVCRepository.Models;
    using Telerik.Web.Mvc;
    using System.DirectoryServices;
    using System.DirectoryServices.AccountManagement;
    using System.Web.Security;
    using TMVCRepository.DataAccessLayer;

      namespace TMVCRepository.Controllers
    {
        public class ActivedirectoryController : Controller
        {

            public ActionResult Index()
            {
                return View();
            }





            [HttpPost]

            public ActionResult index(ActivedirectoryModels UC)
            {


                if (ModelState.IsValid) 
                {


                    string userid = Request.Form["UserID"];
                    string password = Request.Form["Password"];
                    string domainname = Request.Form["DomainName"];


                    return RedirectToAction("submit",
                                "Activedirectory",
                                new { userid = userid, password = password, 
      domainname = domainname });

                }

                else
                {

                    ModelState.AddModelError("", "Error in Viewing data");

                    return View();

                }

            }
            public ActionResult submit(string userid, string password, string 
      domainname)
            {
                string group1 = null;
                string group2 = null;
                string group3 = null;
                string group4 = null;
                string group5 = null;


                try
                {
                    bool value = IsAuthenticated(domainname, userid, password);


                    if (value == true)
                    {
                        DBclass obj1 = new DBclass();
                        string result = obj1.chkuserentry(userid);
                        if (result == "Yes")
                        {
                           FormsAuthentication.SetAuthCookie(userid, true);

                            // begin


                         using (var context1 = new PrincipalContext(ContextType.Domain, domainname))
                            {
                                if(userid!="testadmin")
                                {
                                using (var exuser = UserPrincipal.FindByIdentity(context1, userid))
                                {
                                    var groups = exuser.GetGroups();

                                string group_name = null;
                                foreach (object obj in groups)
                                {
                                    group_name += "~" + obj.ToString();

                                }

                                group_name = group_name.Replace("~Domain 
  Users","");


                                //oadd split code 

                                string[] strTemp = group_name.Split('~');


                                    for (int i = 0; i < strTemp.Length; i++)
                                    {

                                        if (i == 0)
                                        { group1 = strTemp[0]; }
                                        if (i == 1)
                                        { group2 = strTemp[1]; }
                                        if (i == 2)
                                        { group3 = strTemp[2]; }
                                        if (i == 3)
                                        { group4 = strTemp[3]; }
                                        if (i == 4)
                                        { group5 = strTemp[4]; }



                                    }



                                    if (group1 == null || group1 == "")
                                    { group1 = "N/A"; }
                                    if (group2 == null || group2 == "")
                                    { group2 = "N/A"; }
                                    if (group3 == null || group3 == "")
                                    { group3 = "N/A"; }
                                    if (group4 == null || group4 == "")
                                    { group4 = "N/A"; }
                                    if (group5 == null || group5 == "")
                                    { group5 = "N/A"; }



                                DBclass obj2 = new DBclass();


                                string result1 = obj1.Exist_user(userid, group1, 
 group2, group3, group4, group5);    



                            }
                        }

                    }

                        //end


                        return RedirectToAction("Index", "Home");

                    }

                    else
                    {

                        using (var context = new 
  PrincipalContext(ContextType.Domain, domainname))
                        {
                            using (var user = 
  UserPrincipal.FindByIdentity(context, userid))
                            {

                                var groups = user.GetGroups();
                                string groupname = "";
                                foreach (object obj in groups)
                                {
                                    groupname += "~" + obj.ToString();

                                }



                                TempData["userid"] = userid;


                                TempData["Password"] = password;
                                TempData["Group"] = groupname;
                                return RedirectToAction("Register", "Account");

                            }
                        }

                    }


                }


                else
                {


                    return View("test");
                }








            }

            catch (Exception ex)
            {


                return View("test");

            }



        }


        public bool IsAuthenticated(string srvr, string usr, string pwd)
        {

            bool authenticated = false;

            try
            {

        DirectoryEntry entry = new DirectoryEntry("LDAP://" + srvr, usr + 
  "@" + srvr,pwd, AuthenticationTypes.Secure);


            }
            catch (DirectoryServicesCOMException cex)
            {

            }


            catch (Exception ex)
            {
                //not authenticated due to some other exception [this is optional]
            }

            return authenticated;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

如果用户未登录您的网络应用程序,您会如何考虑获取其用户名?

你不能。

它在开发过程中起作用的事实是因为您要求运行哪个用户的 Web服务器,并且开发服务器在开发人员的帐户下运行。

答案 1 :(得分:0)

要在混合身份验证模式下获取自动身份验证,您要问的是这个吗? 然后我可以回答它为否,它是不可能的,换句话说,从来没有做过实际的