Search code examples
asp.net.net-4.0httpcontext

Will the domain name ever be absent from HttpContext.Current.User.Identity?


I'm working on a simple one page ASP.Net site used inside the company by a limited number of users.

In it, I use HttpContext.Current.User.Identity to get the logged user's name in the format Domain\ActiveDirectoryUserName and stripping out the domain name as suggested by the answer in this post: Built-in helper to parse User.Identity.Name into Domain\Username and display it in a label like Hello xyz

Will there ever be a scenario, where the Domain name will not be present in HttpContext.Current.User.Identity?


UPDATE: This site uses Windows Authentication


Solution

  • Firstly, if the user is anonymous, you'll get an empty string for the user's identity.

    Secondly, there is only a domain present when you're using an authentication source which supports domains. If you're using Windows Integrated Authentication under IIS, the domain will always be present in every non-anonymous user identity. If you're using forms authentication or another authentication source, the provider has full control over the format of the user's identity.


    As you've indicated you're using Windows Integrated Authentication, you'll always have a domain, provided the user is authenticated. If you allow anonymous access, you should check that HttpContext.Current.User.IsAuthenticated first before trying to parse their name.