简体   繁体   中英

How to get the username of windows authenticated user in asp.net?

I have an single page application running in our Intranet. Users are authenticated by Windows Authentication (their domain-user). When clicking a button I want to send a request (using $http, Angular) to an aspx-page that has the following code:

        string result = "Unknown";
        var loggedOnUser = System.Security.Principal.WindowsIdentity.GetCurrent();
        if (loggedOnUser != null) {
            int index = loggedOnUser.Name.LastIndexOf("\\", StringComparison.Ordinal) + 1;
            result = loggedOnUser.Name.Substring(index);
        }
        var json = "{ \"User\" : \"" + result + "\"}";
        Response.Clear();
        Response.ContentType = "text/json";
        Response.Write(json);
        Response.End();

This code only gives me the name of the user that is registered in the Application Pool. Thats not very surprising indeed so I guess I need to do some impersionating here? The reason for doing this is that I want the username in my javascript so that it can be sent as a paramter in other calls to the server. I have searched the web and everyone says that getting the logged-in users username is a big security breach. And I do see that. But I may be a workaround when it is done in a way that involve server-code?

Any suggestions?

Thanks!

I got like this on Login click

 protected void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            string UserName = "";
            string activeDomain = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
            string strName = HttpContext.Current.User.Identity.Name.ToString();


            if (strName == "")
            {
                UserName = activeDomain;
            }
            else
            {
                UserName = strName;
            }

            if (UserName == "")
            {
                lblMsg.Text = "Invalid Credentials. Please contact administrator!";
            }
            else
            {
                LP.UserName = UserName;
                DataSet dsUserName = LBLL.validate_user(LP);
                if (dsUserName.Tables[0].Rows.Count > 0)
                {
                    Session["UserName"] = dsUserName.Tables[0].Rows[0]["userName"].ToString();
                    Session["entityUID"] = dsUserName.Tables[0].Rows[0]["entityUID"].ToString();
                    Response.Redirect("~/index.aspx", false);
                }
                else
                {
                    lblMsg.Text = "Invalid Credentials. Please contact administrator!";
                }
            }
        }
        catch (Exception ex)
        {

        }
    }

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