Mr_Hmp
Mr_Hmp

Reputation: 2535

How to check domain name of user without logging in

I have a MVC 5 application which uses OWIN and identity2.0 for authentication. My application require mixed authentication:

I want to know how can I get the domain name of user without authentication, at the time when user first hit my Account/Login action.

I have used :

PrincipalContext pcontext = new PrincipalContext(ContextType.Domain);
var domainName = pcontext.ConnectedServer;

and

System.Security.Principal.WindowsIdentity context = System.Security.Principal.WindowsIdentity.GetCurrent();
var domainName = pcontext.Name;

BUT both of these shows domain name of machine where website is deployed and not of the client's domain.

Any help is much appreciated and please correct me if I am doing any blunder.

Upvotes: 1

Views: 1884

Answers (2)

Daniel Mohr
Daniel Mohr

Reputation: 714

The domain can be seen here

Environment.UserDomainName

Gets the network domain name associated with the current user.

Per the MSDN documentation:

The UserDomainName property first attempts to get the domain name component of the Windows account name for the current user. If that attempt fails, this property attempts to get the domain name associated with the user name provided by the UserName property. If that attempt fails because the host computer is not joined to a domain, then the host computer name is returned.

If you're not authenticated, you'll unfortunately see the host computer name. No way around this that I'm aware of.

You can also get the ip of the client's request here

HttpRequest.UserHostAddress

Upvotes: 1

Gabriel Luci
Gabriel Luci

Reputation: 40938

"without authentication"? You can't. The Windows authentication has to be completed before you can see the user's account.

This is because of how Windows authentication works:

  1. The browser accesses the site anonymously.
  2. IIS returns a 401 response
  3. The browser responds by making the request again with the Windows credentials included
  4. IIS verifies the credentials with the domain controllers
  5. IIS passes the verified Windows credentials to your application.

The only time your application can see anything about the user's account is at step 5 - after the authentication is successfully complete.

Upvotes: 2

Related Questions