18

I was wondering whether it was possible to obtain the current user object and get their credentials so that I can pass them along to a NetworkCredential object which I am using to connect to my AX .NET Business Connector. As, at the moment I'm having to specify it connect as a specific user which I set when I instantiate a NetworkCredential object:

private NetworkCredential nc = new NetworkCredential("myUser", "myPassword", "myDomain");

I was hoping to do something like: private NetworkCredential nc = (NetworkCredential)HttpContext.User; but obviously that won't work...

That way, it's easier to keep track of which user has created a sales order for example, as at the moment everything gets created by the user I have specified..

CallumVass
  • 11,288
  • 26
  • 84
  • 154

3 Answers3

36

CredentialCache.DefaultNetworkCredentials?

The credentials returned by DefaultNetworkCredentials represents the authentication credentials for the current security context in which the application is running. For a client-side application, these are usually the Windows credentials (user name, password, and domain) of the user running the application.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • 3
    When I used this, the credential are all empty strings? – CallumVass Jul 10 '12 at 14:45
  • 4
    It returns a `SystemNetworkCredential`, an internal class that derives from `NetworkCredential`. There's hidden magic inside it, but it deliberately sets the username, password, etc as empty strings, if that's what you're referring to. – Damien_The_Unbeliever Jul 10 '12 at 14:50
  • Well, I cant use this way anyway as I wanted to pass the object along to a WCF Web service.. but seems this is not possible.. thanks for your help.. – CallumVass Jul 10 '12 at 14:58
5

I don't fully understand your question, but is your call coming from ASP.NET that you require the credentials? You could attempt:

Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");

Assuming your user has already authenticated via a Membership Provider.

Jaime Torres
  • 10,365
  • 1
  • 48
  • 56
  • 3
    I'm using an ASP.NET MVC 3 Windows Authentication application, so I assume they've been authenticated? When I look at `credential` all of the fields are empty strings? – CallumVass Jul 10 '12 at 14:44
0

A combination of the above worked great for me to resolve the authentication.

var credentials = new NetworkCredential();
ICredentials credent = CredentialCache.DefaultNetworkCredentials;
credentials = (NetworkCredential)credent;
var serverId = new LdapDirectoryIdentifier(GlobalVariables.LDAPServer);

LdapConnection connection = new LdapConnection(serverId, credentials);
connection.Bind();