I am following this tutorial http://wiki.developerforce.com/page/Integrating_Force.com_with_Microsoft_.NET
However, I am getting this error:
LOGIN_MUST_USE_SECURITY_TOKEN: Invalid username, password, security
token; or user locked out. Are you at a new location? When accessing
Salesforce--either via a desktop client or the API--from outside of
your company’s trusted networks, you must add a security token to your
password to log in. To receive a new security token, log in to
salesforce.com at http://login.salesforce.com and click Setup | My
Personal Information | Reset Security Token.
This is my code in my Console App:
static void Main(string[] args)
{
string userName;
string password;
userName = "me#myWebsite.com";
password = "myPassword";
SforceService SfdcBinding = null;
LoginResult CurrentLoginResult = null;
SfdcBinding = new SforceService();
try
{
CurrentLoginResult = SfdcBinding.login(userName, password);
}
catch (System.Web.Services.Protocols.SoapException e)
{
// This is likley to be caused by bad username or password
SfdcBinding = null;
throw (e);
}
catch (Exception e)
{
// This is something else, probably comminication
SfdcBinding = null;
throw (e);
}
}
The error states I need a security token, but the documentation never seems to mention it and I'm not sure how to get one.
What I had to do (which was not in the documentation) is go to here:
https://na15.salesforce.com/_ui/system/security/ResetApiTokenConfirm?retURL=%2Fui%2Fsetup%2FSetup%3Fsetupid%3DPersonalInfo&setupid=ResetApiToken
And, reset my token. Then, append it to the end of my password like:
If your password = "mypassword"
And your security token = "XXXXXXXXXX"
You must enter "mypasswordXXXXXXXXXX" in place of your password
Ref. http://docs.servicerocket.com/pages/viewpage.action?pageId=83099770
With a SOAP API like this you need to authenticate to the service first by providing the username and password. Their response should return an authorization token that will be valid for a period of time. Then in your subsequent communications you pass this token to the API so that it knows who you are.
Get the authorization token:
SforceService SfdcBinding = null;
LoginResult CurrentLoginResult = null;
SfdcBinding = new SforceService();
try
{
CurrentLoginResult = SfdcBinding.login(userName, password);
}
catch (System.Web.Services.Protocols.SoapException e)
{
// This is likely to be caused by bad username or password
SfdcBinding = null;
throw (e);
}
catch (Exception e)
{
// This is something else, probably communication
SfdcBinding = null;
throw (e);
}
Setup the session:
//Change the binding to the new endpoint
SfdcBinding.Url = CurrentLoginResult.serverUrl;
//Create a new session header object and set the session id to that returned by the login
SfdcBinding.SessionHeaderValue = new SessionHeader();
SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;
Perform your query:
QueryResult queryResult = null;
String SOQL = "select FirstName, LastName, Phone from Lead where email = 'john.smith#salesforce.com'";
queryResult = SfdcBinding.query(SOQL);
Related
I'm trying to connect to AWS Cognito from a .net Framework project.
I can sign up succesfully but when I need to sign in, throws me an error: "User pool {userPool} client does not exist".
This is my code:
private async Task<bool> CheckPasswordAsync(string userName, string password)
{
try
{
var authReq = new AdminInitiateAuthRequest
{
UserPoolId = ConfigurationManager.AppSettings["USERPOOL_ID"],
ClientId = ConfigurationManager.AppSettings["CLIENT_ID"],
AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH,
};
authReq.AuthParameters.Add("USERNAME", userName);
authReq.AuthParameters.Add("PASSWORD", password);
AdminInitiateAuthResponse authResp = await _client.AdminInitiateAuthAsync(authReq);
var auts = authResp;
return true;
}
catch(Exception ex)
{
var exc = ex.Message;
return false;
}
}
I don't know if I need to ad more information to the method.
The user pool exists and is the same that I have in appSettings.
Any idea about what's wrong?
Thanks in advance.
I am trying to check if the user is successfully logged in to Axosoft. The code bellow never throws an error, even if the user provides the wrong credentials.
public void Login(string user, string pwd)
{
try
{
AxoClient.ObtainAccessTokenFromUsernamePassword
(
username: user,
password: pwd,
scope: ScopeEnum.ReadWrite
);
}
catch (AxosoftAPIException<ErrorResponse> ex)
{
ErrorResponse er = new ErrorResponse();
er.Error = ex.Source;
er.ErrorDescription = ex.StackTrace;
er.Message = ex.Message;
throw new AxosoftAPIException<ErrorResponse>(er);
}
}
I found the solution for my problem.
After a login you can get the value of the HasAccessToken in Proxy.
If you successfully logged in it will return true, otherwise it'll return false.
Proxy AxoClient = new Proxy
{
Url = "http://url",
ClientId = "ClientId",
ClientSecret = "ClientSecret",
};
AxoClient.ObtainAccessTokenFromUsernamePassword
(
username: user,
password: pwd,
scope: ScopeEnum.ReadWrite
);
MessageBox.Show(AxoClient.HasAccessToken);
I hope this will help others.
I'm getting stuck with creating Active Directory User with C#
this is my code use to create a new user:
public bool CreateUser(string userName, string password)
{
try
{
DirectoryEntry entry = new DirectoryEntry(lDAPConnectionString, aDConnectionUserName, aDConnectionPassword, AuthenticationTypes.Secure);
// Use the Add method to add a user to an organizational unit.
DirectoryEntry user = entry.Children.Add("CN=" + userName, "user");
// Set the samAccountName, then commit changes to the directory.
user.Properties["samAccountName"].Value = userName;
user.Properties["userPrincipalName"].Value = userName + Constants.ADProperties.ADUPNLogonSuffix;
user.CommitChanges();
// Set password never expire
int NON_EXPIRE_FLAG = 0x10000;
int val = (int)user.Properties["userAccountControl"].Value;
user.Properties["userAccountControl"].Value = val | NON_EXPIRE_FLAG;
user.CommitChanges();
// Enable User
val = (int)user.Properties["userAccountControl"].Value;
user.Properties["userAccountControl"].Value = val & ~(int)Constants.ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE;
user.CommitChanges();
user.RefreshCache();
// Set password
user.UsePropertyCache = true;
user.Invoke("SetOption", new object[] { Constants.ADS_USER_FLAG_ENUM.ADS_OPTION_PASSWORD_PORTNUMBER, Constants.ADProperties.ADPort });
user.Invoke("SetOption", new object[] { Constants.ADS_USER_FLAG_ENUM.ADS_OPTION_PASSWORD_METHOD, Constants.ADS_USER_FLAG_ENUM.ADS_PASSWORD_ENCODE_CLEAR });
user.Properties["LockOutTime"].Value = 0;
user.Invoke("SetPassword", new object[] { password });
user.CommitChanges();
return true;
}
catch (Exception)
{
}
return false;
}
And when I use it, it throw an exception : "The server is unwilling to process the request. (Exception from HRESULT: 0x80072035)"
at line : "user.Invoke("SetPassword", new object[] { password });"
I tried many way but I cannot solve this problem.
Any help would be appricated.
Thanks
Error 0x80072035 usually returns due to a password policy. This can be length, special characters, password history (password was used before). It would help to handle those errors to prrovide feedback to the user. A guide to handle these errors can be found here:
http://www.ozkary.com/2015/03/active-directory-setpassword-or.html
I'm building a web application using the default master template in VS2010 - very new to doing this. I'm also using the Login.aspx page, but instead of using the built in user validation, my user info is in a database table. So Following instructions I found, I'm doing something wery similar to this:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
Boolean bauthenticated = false;
bauthenticated = isValidUser(Login1.UserName, Login1.Password);
if (bauthenticated)
{
e.Authenticated = true;
}
else
{
e.Authenticated = false;
}
}
The problem is that I put the method isValidUser in a .dll so it could be used elsewhere, and it is not receiving the password because the default behaivor is to blank it out. I even tried to set a string variable to Login1.Password, and pass the variable without success. I understand why this is happening, but can't find any info as to how to do this correctly. Do I need to put the user name and password into an object and pass that to my class constructor? I really don't want to connect to my database from every Login.aspx page I create to avoid sending the password over http.
Try to use the following code.
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
dtUserDetails = new DataTable();
if (UserRepositoryBL.ValidateUser(LoginUser.UserName.Trim(), LoginUser.Password.Trim(), out dtUserDetails))
{
AuthUser au = new AuthUser();
if (dtUserDetails.Rows.Count > 0)
{
DataRow DR = dtUserDetails.Rows[0];
au.UserID = Convert.ToInt32(DR["UserID"].ToString());
au.UserNo = DR["UserNo"].ToString();
au.UserName = DR["UserName"].ToString();
au.Password = DR["Password"].ToString();
}
string userData = au.ToString();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Version number
LoginUser.UserName.Trim(), // Username
DateTime.Now, // Issue date
DateTime.Now.AddMinutes(60), // Expiration date
false, // Persistent?
userData // User data
);
string eticket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie
(FormsAuthentication.FormsCookieName, eticket);
Response.Cookies.Add(cookie);
BasePage.ActivityLog("User Login", LoginUser.UserName.Trim(), true, Request.RawUrl);
string url = FormsAuthentication.GetRedirectUrl(LoginUser.UserName, false);
Response.Redirect(url);
// FormsAuthentication.RedirectFromLoginPage(LoginUser.UserName, false);
}
else
{
LoginUser.FailureText = "Your login attempt was not successful. Please try again.";
}
}
catch (Exception ex)
{
throw ex;
}
}
dtUserDetails is a out parameter which contains the user details like password,username,etc.. on successful login.datatable returns empty if invalid login.with in userData string all those information will be available.then u can retrieve those from any page using User Authenticated Ticket
I want to add a new user to newly created database and if this user exists then i will connect to that database.
My code is:
public CreateDatabaseOperationResult CreateDatabase(string databaseName,string username,string password, MongoServer server)
{
CreateDatabaseOperationResult createDatabaseOpResult = new CreateDatabaseOperationResult();
string message = null;
MongoCredentials credentials = new MongoCredentials(username, password);
MongoUser user = new MongoUser(credentials, false);
try
{
if (IsDatabaseNameValid(databaseName, out message))
{
if (server.DatabaseExists(databaseName, admincredentials) == true)
{
createDatabaseOpResult.Database = server.GetDatabase(databaseName, credentials);
MongoUser tempuser = createDatabaseOpResult.Database.FindUser(username);
if (tempuser.Equals(user))
{
//createDatabaseOpResult.DatabaseExists = true;
createDatabaseOpResult.IsOperationSuccessfull = false;
throw new ArgumentException("Database Already exist with different set of credentials ");
}
}
else
{
createDatabaseOpResult.Database = server.GetDatabase(databaseName, credentials);
createDatabaseOpResult.Database.AddUser(user);
//createDatabaseOpResult.DatabaseExists = false;
}
createDatabaseOpResult.IsOperationSuccessfull = true;
}
}
catch (MongoQueryException ex)
{
createDatabaseOpResult.Error = ex;
}
//catch (MongoAuthenticationException ex)
//{
// createDatabaseOpResult.Error = ex;
//}
catch (MongoException ex)
{
createDatabaseOpResult.Error = ex;
}
catch (ArgumentException ex)
{
createDatabaseOpResult.Error = ex;
}
return createDatabaseOpResult;
}
When i use the existing database it connects to that database but when i try to add new use Database.AddUser gives error 'invalid credentials for this database'
Please see the error and reply
Most people use the mongo shell to add and remove users, but if you really want to do it in C# the trick is to use the right credentials depending on what you are trying to do. Assume you have the following two sets of credentials, one for the admin database and one for regular databases:
var adminCredentials = new MongoCredentials("myadminusername", "myadminpassword", true);
var userCredentials = new MongoCredentials("myusername", "myuserpassword");
Note that when creating the adminCredentials you must pass true to the admin parameter.
To test if a database exists requires admin credentials:
if (server.DatabaseExists("mydatabase", adminCredentials))
{
// database exists
}
To add a user requires admin credentials:
var myDatabaseWithAdminCredentials = server.GetDatabase("mydatabase", adminCredentials);
if (myDatabaseWithAdminCredentials.FindUser("myusername") == null)
{
myDatabaseWithAdminCredentials.AddUser(userCredentials);
}
Normally you use regular user credentials to work with a database:
var myDatabaseWithUserCredentials = server.GetDatabase("mydatabase", userCredentials);
var count = myDatabaseWithUserCredentials.GetCollection("mycollection").Count();
Also, keep in mind that each database can have any number of users, so you don't really need to be checking whether the database already exists with a different set of credentials.