I am trying to connect Salesforce api via C#. I have reset the security token and added it to the my password then i tried to connect. But login is failed. What am i doing wrong ? Any help would be appriciated.
Login function:
public void sForceLogin(String userName, String password)
{
try
{
currentLoginResult = sForce.login(userName, password);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Console.WriteLine("An exception has been catched:" + ex.Message);
}
}
Main:
SForceTest sft = new SForceTest();
sft.sForceLogin("example#example.com", "password+securitytoken");
You can use following code to login into salesforce.
using (SforceService service = new SforceService())
{
LoginResult loginResult =
service.login(username, String.Concat(password, securityToken));
this.SessionID = loginResult.sessionId;
this.ServerUrl = loginResult.serverUrl;
}
Salesforce login api requires username, password and the security token.
Related
I am trying to schedule a job on an HPC Server 2019 cluster. I would like to do this without having to enter the password of the service account that I am using. Below is the code but the without commenting the line of code it fails to connect
string userName = GetKeyVaultSecret("ServiceAccount");
string password = GetKeyVaultSecret("ServiceAccountPassword");
using (IScheduler scheduler = new Scheduler())
{
try
{
// Connect to the scheduler as another user
Console.WriteLine("Connecting to {0} as {1}...", clusterName, userName);
scheduler.SetCachedCredentials(userName,password); // If I comment this line I am prompted for a password and it connects
scheduler.ConnectServiceAsClient(clusterName, () => userName);
}
catch (Exception e)
{
Console.Error.WriteLine("Could not connect to the scheduler: {0}", e.Message);
if (e.InnerException != null) Console.WriteLine(e.InnerException.Message.ToString());
return 1;
}
The mistake was that I should not be setting the username and password here but when I submit the job
scheduler.SubmitJob(job, #"domain\" + userName, password);
I am connecting successfully to the LDAP with PHP, tried a whole lot of things but when I try with C# am always getting either "Server is not operational" or "The LDAP server in unavailable".
Here is the PHP code:
<?php
function login($username='user', $password='pass') {
if (empty($username) || empty($password)) {
throw new BadCredentialsException('Invalid username or password.');
}
if (($ldap = #ldap_connect($url = 'ldap://ds.xyz-example.com', $port = 636)) === false) {
echo('Error connecting LDAP server with url %s on port %d.');
}
if (!#ldap_bind($ldap, sprintf($dn='uid=%s,ou=People,dc=xyz-example,dc=com', $username), $password)) {
$error = ldap_errno($ldap);
if ($error === 0x31) {
echo('Invalid username or password.');
} else {
echo('error during authentication with LDAP.');
}
}
return true;
}
login(); // call the function
?>
This is working perfect but I need it with C#. How can I do this with C# using the port and the dn and the user and pass?
Here is what I tried with C# but with an error "Server is not operational"
string ldapPath = "LDAP://ds.xyz-example.com:636/UID=user,OU=People,DC=xyz-example,DC=com";
string user = "user";
string password = "pass";
DirectoryEntry deSSL = new DirectoryEntry(ldapPath, user, password, AuthenticationTypes.SecureSocketsLayer);
try
{
user = deSSL.Properties["uid"][0].ToString(); //if this works, we bound successfully
Response.Output.Write("Success... {0} has bound", user);
}
catch (Exception ex)
{
Response.Output.Write("Bind Failure: {0}", ex.Message);
}
Thanks in advance!
Could it be your library doesn't implement LDAP but rather a weird non-standard Microsoft version of LDAP called ActiveDirectory, which only works when the server is an actual ActiveDirectory Server and doesn't quite work as easily when you use non-microsoft servers, such as OpenLDAP?
Could it be?
We are using below code to authenticate user credentials,
string domainAndUsername = this.activeDirectoryConfiguration.Domain + #"\" + username;
DirectoryEntry entry = null;
try
{
entry = new DirectoryEntry(
this.activeDirectoryConfiguration.LdapPath,
domainAndUsername,
password);
// Bind to the native AdsObject to force authentication.
object nativeObject = entry.NativeObject;
if (nativeObject == null)
{
return AuthenticationDetails.InvalidCredentials;
}
}
catch (DirectoryServicesCOMException directoryServicesComException)
{
return this.CheckErrorResponse(username, directoryServicesComException);
}
finally
{
if (entry != null)
{
entry.Dispose();
}
}
This code works fine when using NTLM authentication. Here we are checking error code we get from the 'DirectoryServicesCOMException' to identify whether account is locked or disabled or if the password is expired.
In our production environment, kerberos authentication is used where this code is failing. It throws System.Runtime.InteropServices.COMException which doesn't have detailed description about the failure. Every time it just throws
Message=Logon failure: unknown user name or bad password.
Can anyone suggest why isn't Kerberos giving detailed exception or is there any way to identify various login failures while using kerberos?
So I wanted the users to login to my app using Microsoft Account
I did all the setup in my mobile service in Azure and this is how I implement the login in my App:
private async Task<bool> AuthenticateAsync()
{
string message;
bool success = false;
try
{
user = await App.MobileService
.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
message =
string.Format("You are now signed in - {0}", user.UserId);
success = true;
}
catch (InvalidOperationException)
{
message = "You must log in. Login Required";
}
var dialog = new MessageDialog(message);
dialog.Commands.Add(new UICommand("OK"));
await dialog.ShowAsync();
return success;
}
all is working fine but all I get from this is a User Id.
and I need the name of the user that logged in, can anyone help me how should I go about this?
Thanks
and I need the name of the user that logged in, can anyone help me how should I go about this
For UWP app, this is impossible using official managed API. See MobileServiceAuthentication class in here
internal async Task<MobileServiceUser> LoginAsync()
{
string response = await this.LoginAsyncOverride();
if (!string.IsNullOrEmpty(response))
{
JToken authToken = JToken.Parse(response);
// Get the Mobile Services auth token and user data
this.Client.CurrentUser = new MobileServiceUser((string)authToken["user"]["userId"]);
this.Client.CurrentUser.MobileServiceAuthenticationToken = (string)authToken[LoginAsyncAuthenticationTokenKey];
}
return this.Client.CurrentUser;
}
The official sdk just retrieves the userId and MobileServiceAuthenticationToken, for other platform, we need to use GetIdentitiesAsync() method to get identity, see How to get user name, email, etc. from MobileServiceUser? or LINK
The username info actually has been retrieved in the SSO process:
So you have to implement the auth process(Extend the method based on the open source code) and maintain the username information as you need.
If you can get the user's input, maybe you can also call Live API: https://msdn.microsoft.com/en-us/library/office/dn659736.aspx#Requesting_info
I have the following code as part of a web application for my Active Directory users to be able to update their passwords (for active directory and gmail at the same time). I am using C# with System.DirectoryServices.AccountManagement.
This code worked until yesterday
try
{
State.log.WriteLine("Connecting LDAP.");
string ldapPath = "LDAP://192.168.76.3";
DirectoryEntry directionEntry = new DirectoryEntry(ldapPath, domainName + "\\" + userName, currentPassword);
if (directionEntry != null)
{
DirectorySearcher search = new DirectorySearcher(directionEntry);
State.log.WriteLine("LDAP Connected, searching directory for SAMAccountName");
search.Filter = "(SAMAccountName=" + userName + ")";
SearchResult result = search.FindOne();
if (result != null)
{
State.log.WriteLine("Getting User Entry.");
DirectoryEntry userEntry = result.GetDirectoryEntry();
if (userEntry != null)
{
State.log.WriteLine("Setting Password");
if (force)
{
userEntry.Invoke("SetPassword", new[] { newPassword });
}
else
{
userEntry.Invoke("ChangePassword", new object[] { currentPassword, newPassword });
}
userEntry.CommitChanges();
State.log.WriteLine("Changes Committed to ActiveDirectory.");
}
else
{
State.log.WriteLine("Could not get user Entry...");
}
}
else
{
State.log.WriteLine("Search returned no results.");
}
}
else
{
State.log.WriteLine("Could not connect to LDAP with given username and passwd");
}
}
Since yesterday, this code makes it to the line:
userEntry.Invoke("ChangePassword", new object[] { currentPassword, newPassword });
and then throws the following exception:
[8:37:00 AM] : Password Requirements Met.
[8:37:00 AM] : Connecting LDAP.
[8:37:00 AM] : LDAP Connected, searching directory for SAMAccountName
[8:37:01 AM] : Getting User Entry.
[8:37:01 AM] : Setting Password
[8:37:01 AM] : Failed to reset Windows Password for jason.
Exception has been thrown by the target of an invocation.
The system cannot contact a domain controller to service the authentication request. Please try again later. (Exception from HRESULT: 0x800704F1)
The "force" option using "SetPassword" still works just fine, but the "ChangePassword" method which can be invoked by non-administrator users does not.
Change userPrincipal.ChangePassword("Old pass", "New Pass"); to userPrincipal.SetPassword(model.NewPassword);
I found a work-around and forgot to post it. What I did was use the code above to authenticate the user and then just call my "ForceChangePassword" method:
public static void ForceChangeADPassword(String username, String newPassword)
{
String DN = "";
try
{
DN = GetObjectDistinguishedName(objectClass.user, returnType.distinguishedName, username, DOMAIN_CONTROLLER_IP);
}
catch(Exception e)
{
throw new PasswordException(String.Format("Could not find AD User {0}", username), e);
}
if(DN.Equals(""))
throw new PasswordException(String.Format("Could not find AD User {0}", username));
DirectoryEntry userEntry = new DirectoryEntry(DN.Replace("LDAP://", LdapRootPath), "accounts", AcctPwd);
userEntry.Invoke("SetPassword", new object[] { newPassword });
userEntry.Properties["LockOutTime"].Value = 0;
userEntry.CommitChanges();
userEntry.Close();
}
Earlier this month Microsoft released a security patch, resolving some vulnerabilities in the area of password change. Specifically, the update blocked fallback to NTLM authentication after a failed Kerberos authentication when changing a password.
You might want to read more about the update here.
Microsoft has updated this article: https://support.microsoft.com/en-us/kb/3177108 . Here they have given us problems created by the original "fixes" as well as some tips for working with Kerberos and self-service password reset.
As of October 11, 2016 Microsoft re-released the patches associated with https://technet.microsoft.com/en-us/library/security/ms16-101.aspx to resolve issues caused by the original updates (which you can read in https://support.microsoft.com/en-us/kb/3177108 including the fact that you could no longer change passwords on local accounts).