/* * @description Authenticates the user with Salesforce via a connected OAuth application. * * @param username The user's Salesforce username. * @param password The user's Salesforce password * * @throws SalesforceConfigurationException if client is not properly configured * @throws SalesforceApiException if authentication request fails (possible reasons: network, credentials...) */ public IEnumerator login(string username, string password) { // Check configuration assertConfigurationIsValid(username, password); // Check if Auth Token is already set if (isUserLoggedIn()) { yield return(true); } // Configure query WWWForm form = new WWWForm(); form.AddField("username", username); form.AddField("password", password); form.AddField("client_secret", consumerSecret); form.AddField("client_id", consumerKey); form.AddField("grant_type", "password"); WWW www = new WWW(oAuthEndpoint, form); // Execute query & wait for result yield return(www); // Check query result for errors if (www.error == null) { logHttpResponseSuccess(www, "GET"); JSONObject obj = JSONObject.Parse(www.text); string token = obj.GetString("access_token"); string instanceUrl = obj.GetString("instance_url"); connection = new SalesforceConnection(token, instanceUrl, apiVersion); yield return(true); } else { logHttpResponseError(www, "GET"); JSONObject errorDetails = JSONObject.Parse(www.text); if (errorDetails != null) { string error = errorDetails.GetString("error"); string errorDescription = errorDetails.GetString("error_description"); if (error == "invalid_client_id" || error == "invalid_client") { throw new SalesforceConfigurationException("Salesforce authentication error due to invalid configuration: " + errorDescription); } else if (error == "invalid_grant") { throw new SalesforceAuthenticationException("Salesforce authentication error due to invalid user credentials: " + errorDescription); } else { throw new SalesforceApiException("Salesforce authentication error: " + errorDescription); } } throw new SalesforceApiException("Salesforce authentication error: " + www.error.ToString()); } }
/** * Allows to resume an already open connection and save time by not logging in again. */ public void setConnection(SalesforceConnection connection) { this.connection = connection; }