Jakub Wisniewski
Jakub Wisniewski

Reputation: 2249

How to retrieve the currently logged on user

I have writen my own session based authentication. In Global.asax I have added this function that takes enviroment username and check if it exist in database:

Protected Sub Session_Start(sender As Object, e As EventArgs)

    Dim userData As UserLogin = _
        New UserLogin(Convert.ToString(Environment.UserName))

    If userData.IsValid Then
        Authentication.SaveUserToSession(userData)
    End If
End Sub

And this is how i save userstate to session in authentication class:

Public Shared Sub SaveUserToSession(user As UserLogin)

    HttpContext.Current.Session("Username") = user.Username
    HttpContext.Current.Session("isValid") = user.IsValid
    HttpContext.Current.Session("isAdmin") = user.IsAdmin
    HttpContext.Current.Session("ID") = user.Id

End Sub

When I display in view:

<ul >
    <li>Welcome @HttpContext.Current.Session("Username")</li>
</ul>

Everyone sees the same username. Why is this happening?

Upvotes: 0

Views: 1067

Answers (3)

Martin Liversage
Martin Liversage

Reputation: 106826

If you want to create an intranet web site that authenticates users logged into a Windows domain you can use ASP.NET Identity with Windows Authentication. You have to change authentication to Windows Authentication:

Windows Authentication

Normally, when you access Environment.UserName the get the name of the user owning the executing process and in ASP.NET this user is a service account (and not the user sending the request from a web browser). However, when you use Windows Authentication this behavior changes and you can now use Environment.UserName to get the name of the remote user. Obviously, this only works on an intranet with a Windows domain.

Really, you should not use Environment.UserName in an ASP.NET application because it changes behavior based on the authentication used. Instead you can inspect the User property which is available in both the controller and view in ASP.NET applications based on the newest versions of the framework and it will give you information about the remote user if he or she is logged in.

Upvotes: 1

L-Four
L-Four

Reputation: 13531

System.Environment.UserName returns the identity under which the application pool that hosts your web site is running.

So in your case this is always your account.

So depending on the security method you have implemented you have to use the appropriate way to retrieve the currently logged on user name.

Upvotes: 2

Nanhydrin
Nanhydrin

Reputation: 4472

As per the MSDN documentation Environment.UserName "Gets the user name of the person who is currently logged on to the Windows operating system.".

So it's no use to you for getting the user that's logging into your website, and because you're always the user who is logged into the OS everyone will always get your data.

Upvotes: 1

Related Questions