-1

My legacy ASP.NET Framework 4.5 (Windows auth) web site running in IIS uses the following code to get the Windows user id (to assess permissions):

String Name = System.Environment.UserName;

Looking at a log of this string, the Windows user ID isn't obtained correctly; rather, the name corresponding to the application pool credentials is obtained.

Is this due to using impersonation in web.config:

<identity impersonate="true" userName="app_user" password="xxxx" />

Or can I change a setting in IIS to correct this?

The web site used to work correctly. Something was changed in IIS and now it doesn't...

In web.config, windows authentication is specified:

<system.web>
<compilation debug="true" defaultLanguage="c#" targetFramework="4.5" />
<authentication mode="Windows" />. . .

UPDATE: by enabling Anonymous Authentication (impersonation) in IIS for the web application itself, I was able to overcome this issue.

user2132190
  • 373
  • 1
  • 2
  • 17
  • 2
    You should never again set `userName` and `password` in `identity` tag. To configure an identity for the whole web application you should use application pool identity. To query the log on user information in your legacy ASP.NET web apps, use `Page.User` or `Controller.User` please. Don't know how you get started with this web app, but there are tons of samples over the internet telling the right way to go. – Lex Li Dec 18 '21 at 19:11
  • You might read my blog post for more details, https://blog.lextudio.com/miseries-around-asp-net-windows-authentication-setup-14e2e8522ad2 – Lex Li Dec 18 '21 at 19:34

1 Answers1

0

uses the following code to get the Windows user id (to assess permissions):

String Name = System.Environment.UserName;

If you already implemented the Windows auth within your ASP.NET app (actually, the following code is enough):

<configuration>
  <system.web>
    ...
    <authentication mode="Windows"></authentication>
  </system.web>
</configuration>

Retrieve the necessary info via the System.Web.HttpContext.Current.User / System.Web.HttpContext.Current.User.Identity.Name property value (wherever you are - ASPX Page Code Behind, ASP.NET MVC Controller, any ASP.NET app module):

Check out some related threads to understand the differences: System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET

ASPX Page Code Behind:

protected void Page_Load(object sender, EventArgs e) {
    //Page.User
    ...
}

ASP.NET MVC Controller:

public class HomeController : Controller {
    public ActionResult SomeActionMethod() {
        //User
    }
}

any ASP.NET app module:

public class X {
    public void Y() {
        //System.Web.HttpContext.Current.User
    }
}
Mikhail
  • 9,186
  • 4
  • 33
  • 49