Obtain Network Credentials from Current User in Windows Authentication Application - c#

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..

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.

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.

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();

Related

SSRS Forms Authentication - How To Pass Cookie Credentials To Report Server

I am currently attempting to render the SSRS report in my web application using forms authentication.
My SSRS Report Version is 2016.
Initially I was under the impression that NetworkCredentials would work, and after encountering errors, I found that we are required to use FormsAuthentication, with passing the cookie as a means of authenticating the user.
I have done the necessary settings on the config files in the Reporting Server by following the guide from the link below:-
https://github.com/Microsoft/Reporting-Services/tree/master/CustomSecuritySample2016
The reporting services works as intended on the localhost/ReportServer and on
the SSRS Portal, localhost/Reports. I am also able to access said server
remotely.
Below is the code I used to obtain the authenticated cookie.
MyReportingService rsClient = new MyReportingService();
rsClient.Url = "http://xxx.xxx.xxx.xxx/reportserver/ReportService2010.asmx";
try
{
rsClient.LogonUser("user", "password", "");
Cookie myAuthCookie = rsClient.AuthCookie;
HttpCookie cookie = new HttpCookie(myAuthCookie.Name, myAuthCookie.Value);
Response.Cookies.Add(cookie);
}
Which supposedly would then be used to authenticate the user.
Cookie authCookie = new Cookie(cookie2.Name, cookie2.Value);
authCookie.Domain = "DomainName";
rvSiteMapping.ServerReport.ReportServerCredentials = new MyReportServerCredentials(authCookie);
rvSiteMapping.ServerReport.Cookies.Add(authCookie);
And in my forms authentication within the IReportsServerCredentials Class:-
public bool GetFormsCredentials(out Cookie authCookie,
out string user, out string password, out string authority)
{
authCookie = m_authCookie;
user = password = authority = null;
return true; // Use forms credentials to authenticate.
}
The issue I am experiencing is when the application is passing the credentials to the report server. I believe I must be doing this part incorrectly because while my application does get the cookie, when it authenticates the credentials provided by the cookie, I receive the text/html error:-
Object moved to <a href="/ReportServer/logon.aspx?ReturnUrl=%2fReportserver%2fReportExecution2005.asmx" />
This error is in response to setting a default generic Identity in the event that
the HttpContext.Current.User = null.
if (HttpContext.Current != null
&& HttpContext.Current.User != null)
{
userIdentity = HttpContext.Current.User.Identity;
}
else
{
userIdentity = new GenericIdentity("AnonymousUser");
}
I have tried googling the answer but most of the results are for
windows authentication and the few that are related to forms authentication
are very similar to the code I referred to.
The underlying cause of the issue was under my nose the whole time.
The domain name should refer to the web domain and not the active directory domain.
authCookie.Domain = "DomainName";
The cookie is now able to authenticate the user as intended.
Hopefully this helps anyone who happens to make the same mistake.

autenticating ldap for web applications

please take a few minutes and read my question completely. here is my problem :
I want to connect to LDAP server by C# for a web application, means clients connecting to the asp.net server.
*- The ldap server and application server are not the same.
**- They are not in a same domain.
I have been trying 4 different ways and could not solve the problem by none of them.
1-
var credentials = new NetworkCredential(username, password);
var serverId = new LdapDirectoryIdentifier("domain.net");
var conn = new LdapConnection(serverId, credentials);
conn.Bind();
2-
System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://domain.net/DC=domain,DC=net");
entry.Username = "username";
entry.Password = "password";
System.DirectoryServices.DirectorySearcher searcher = new System.DirectoryServices.DirectorySearcher(entry);
searcher.Filter = "(&(objectClass=user))";
var results = searcher.FindAll();
the problem with these 2 ways is that the user must have an access to the server for login and we know that there is only admin of the system who has the permission.
3-
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "domain.net");
var ret = pc.ValidateCredentials(model.UserName, model.Password);
the problem is the server must be in the domain of ldap server. we have this limitation !!
4-
https://auth0.com/blog/using-ldap-with-c-sharp/
public bool validateUser(string username, string password)
{
var sha1 = new SHA1Managed();
var digest = Convert.ToBase64String(sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)));
var request = new CompareRequest(string.Format("uid={0},ou=users,dc=example,dc=com", username),
"userPassword", "{SHA}" + digest);
var response = (CompareResponse)connection.SendRequest(request);
return response.ResultCode == ResultCode.CompareTrue;
}
this code does not return any thing. it will be very helpful if there is a query to compare usernames and passwords. this code seems to use this way but there are different types of hash algorithms. I tried to use SHA1 and MD5, and userPassword , unicodePwd attribute. but the return is empty all the time.
is it the best solution to put both servers in a same domain? any other solution , Thank you so much.
Method 1 is the simplest way. If that doesn't work, nothing will. So you will have to change your configuration to make it work.
When you say:
the user must have an access to the server for login and we know that there is only admin of the system who has the permission.
What do you mean? Are you explicitly denying login rights to the domain controllers? Are there network issues between the computer this is running on and the domain controller (can you hit port 389 on the domain controller(s))?
Update: PrincipalContext.ValidateCredentials just does an LDAP bind in behind - it uses LdapConnection. You can see the source code here. The probable reason why ValidateCredentials is working on a domain machine and not otherwise is because it uses Kerberos authentication by default, which will only work from a domain computer.
The same is true with LdapConnection. So try setting the authentication mode. For example, try Basic
var credentials = new NetworkCredential(username, password);
var serverId = new LdapDirectoryIdentifier("domain.net");
var conn = new LdapConnection(serverId, credentials, AuthType.Basic);
conn.Bind();
Or look at the available values and try what works.

Authenticate user by ADFS (Active Directory Federation Service)

I need to check whether particular user exist OR not in Active Directory by ADFS.
So, I want my ADFS to check user Authentication by UserName/Password.
Could anybody please provide the sample code OR tutorial for the same.
Thanks in advance!
To use Username/Password authentication you can use the
trust/13/UsernameMixed
endpoint of the ADFS 2.0.
This does NOT check if the user exists in the Active Directory!
In code you request the token like this:
WSTrustChannelFactory adfsfactory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
StsEndpoint);
adfsfactory.TrustVersion = TrustVersion.WSTrust13;
// Username and Password here...
factory.Credentials.UserName.UserName = "domain\username";
factory.Credentials.UserName.Password = "password";
IWSTrustChannelContract channel = adfsfactory.CreateChannel();
// request the token
SecurityToken token = channel.Issue(rst);
Then create the channel factory for your service using your token:
var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.Message);
var factory = new ChannelFactory<IYourInterface >(binding, "your service address");
factory.ConfigureChannelFactory();
IYourInterface channel = factory.CreateChannelWithIssuedToken(token);
Hope this helps!
The AD FS 2.0 sign-in pages support username/password authentication out of the box. No code or customizations necessary.
As per #Marnix, this is out the box behavior.
However, just to point out:
Authenticating the user is NOT the same as checking whether a particular user exists in Active Directory.
e.g. the user could be locked out. He still exists in AD but will not be able to authenticate.

Proxy Authentication Required (Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.)

When I was trying to post messages to Twitter, the above error coming. How to get rid of that error?
The stacktrace is the following:
Exception = {"The remote server returned an error: (407) Proxy Authentication Required."} ExceptionStatus = ProtocolError
Code:
private string GetOAuthUrl()
{
IFluentTwitter twitter;
//Override the callback url if one was entered
if (CallbackUrl != null && CallbackUrl.Trim().Length > 0)
{
twitter = FluentTwitter.CreateRequest().Configuration.UseHttps().Authentication.GetRequestToken(ConsumerKey, ConsumerSecret, CallbackUrl);
}
else
{
twitter = FluentTwitter.CreateRequest().Configuration.UseHttps().Authentication.GetRequestToken(ConsumerKey, ConsumerSecret);
}
var response = twitter.Request();
UnauthorizedToken UnauthorizedToken = response.AsToken();
string AuthorizationUrl = FluentTwitter.CreateRequest().Authentication.GetAuthorizationUrl(UnauthorizedToken.Token);
return AuthorizationUrl;
}
If fluent twitter is using WebRequests under the covers, then you need to specify credentials for the proxy using code like this:
System.Net.WebRequest.DefaultWebProxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
This will tell all web requests to use the credentials of the user running the application to authenticate with the proxy.
To make this work, you will need to configure the application to run under a service account which has been granted access to the proxy server. You can then tie down this service account so that it has as few permissions as possible to run the service.
If your application needs to run under an account which doesn't have rights to use the proxy server, you can specify the credentials explicitly as follows:
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password", "domain");
System.Net.WebRequest.DefaultProxy.Credentials = credentials;
The down side to this is that you have to store those credentials somewhere, and that they could be captured by an attacker if they managed to compromise your application. In some environments, this is not acceptable from a security standpoint.

C#/.NET: How to access a network printer share with another user's credentials?

In Windows, when using a local PC account and trying to access the network printer share (ie typing "\printershare" in the Run window), a box pops up asking for a domain user's username and password.
Put in a domain user's username and password, and then the printer share appears using the domain user's credentials.
How can this be achieved via C#?
I have tried the following methods:
var printerShare = new DirectoryEntry(#"\\printershare\", "username", "password");
var printerShare = new DirectoryEntry(#"WinNT://printershare\", "username", "password");
var printerShare = new DirectoryEntry(#"WinNT:\\printershare\", "username", "password");
var printerShare = new DirectoryEntry("LDAP://printershare.corp.domain.com", "username", "password");
var printerShare = new DirectoryEntry("LDAP:\\printershare.corp.domain.com", "username", "password");
Unfortunately, none of them work. Mapping a network directory or folder would be simple.
But the fact that there are no folders is what is making me scratch my head.
Anyone know what I'm doing wrong here?
Check out this question (specifically the NetworkConnection class):
How to provide user name and password when connecting to a network share

Categories