0

How to capture user details like user identity or ip. Currently I am working with c# mvc, my current project is working fine and can capture the user name and ip only in running on debbug mode on my local project but if I am going to publish it to server IIS every client will just get the server info rather than their identity.

Here is my simple current flow:

On my View I have this to display the user name:

<html>
<body>
<a id="test" class="navbar-brand" href="#" style="float:right">User</a>
<html>
</body>

<script>
    $(document).ready(function () {

        $.ajax({
            url: '/Home/getUserInfo',
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                document.getElementById("test").innerHTML = data;
            },
            error: function (jqXhr, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });
</script>

And on my controller I have this function:

public ActionResult getUserInfo()
        {            
            System.Security.Principal.WindowsIdentity user = System.Security.Principal.WindowsIdentity.GetCurrent();

            string name = user.Name;
            return Json(name, JsonRequestBehavior.AllowGet);
        }

Any suggestion/Comments TIA.

Syntax Rommel
  • 932
  • 2
  • 16
  • 40
  • Re username, see [this](https://stackoverflow.com/questions/43688311/how-to-get-windows-username-using-javascript-for-all-browsers) and [this](https://stackoverflow.com/questions/29232208/get-windows-user-name-using-javascript). As for the remote IP, that should be in the `Request` object. – ProgrammingLlama Dec 13 '18 at 00:43
  • 1
    Typically your app would have a login screen and after successful login it establishes a session for the client in the server. Your server side call (`getUserInfo()`) should access this session object and then return the user details. As @John suggested, the IP would be in the Request object – vjgn Dec 13 '18 at 01:24
  • https://stackoverflow.com/questions/125341/how-do-you-do-impersonation-in-net#7250145 helped me in similar situation – Tzwenni Dec 13 '18 at 01:24

1 Answers1

0

This only works if the user have logged in your application

public ActionResult GetUserInfo()
{
    string ip = HttpContext.Request.UserHostAddress;
    string name = HttpContext.Request.RequestContext.HttpContext.User.Identity.Name;
    return Json(new { name = name, ip = ip }, JsonRequestBehavior.AllowGet);
}

If this don't work for you, i think there are some solutions here >> Getting the name of the current Windows user returning "IIS APPPOOL/Sitename"

Ivan Valadares
  • 869
  • 1
  • 8
  • 18