• crtest1
  • NEWBIE
  • 50 Points
  • Member since 2011

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 9
    Replies

Hi Simon,

 

I'd like to get Salesforce Report data with access token. I used HttpClient to setup connection to Salesforce and send request to get report data. In request header, I used cookies and add 'sid' to it. It works well. However, when I switch to OAuth it doesn't work since then. I tried assigning access token to 'sid' as well as removing 'sid' from header and adding 'Authorization: OAuth #access token#' to header of the request without success. The response code is 200 though. The response is a page with redirect to 'https://login.salesforce.com/?ec=302&startURL=/00O50000002HVb2?isExcel=1&xf=csv&export=1&enc=UTF-8'. Following are the codes for sending the request.

                GetMethod get = new GetMethod(url);
		get.setFollowRedirects(true);
		
		get.setRequestHeader("Cookie", "com.salesforce.LocaleInfo=us; inst=APP7");
		get.setRequestHeader("Authorization: OAuth ", accessToken);
		
		int iCode = client.executeMethod(get);

 Please help take a look, and help to point out what could be wrong.

 

Thanks,

Michael

Hi,

 

As I posted in this thread: http://boards.developerforce.com/t5/Security/Using-Partner-WSDL-API-with-OAuth/td-p/302435, Simon mentioned I just need to replace sessionId with access token in the SessionHeader. When i set property to binding in binding._setProperty(SoapBindingStub.ENDPOINT_ADDRESS_PROPERTY, service_url);, what url should I use here? Before I use "https://www.salesforce.com/services/Soap/u/21.0". With OAuth, I have instance_url as "https://na3.salesforce.com" for one user. Should I use this instance_url instead of previous soap url?

 

Thanks,

Michael

Hi,

 

Here is another similar situation, but this time I tried to request for access token with refresh_token in Java. I got error "java.io.IOException: Server returned HTTP response code: 400 for URL: https://login.salesforce.com/services/oauth2/token". It works if I use a self-submitted html form to get access token from Salesforce.

 

Here is the Java codes for the request:

                String tokenUrl = "https://login.salesforce.com/services/oauth2/token";
		HttpURLConnection httpConnection = null;
		DataOutputStream dos = null;
		
		try{
			StringBuilder sb = new StringBuilder("grant_type=refresh_token");
			sb.append("&client_id=").append("3MVG9Km_cBLhsuPy92UAudTyfc9ka4dxuV.OMS5r0vyIS_ThDWpVFBpenmEEUGIHUrBCeHC28ZqbFDWkcCUAd");
			sb.append("&client_secret=").append("7408566340993550860");
			sb.append("&refresh_token=").append("5Aep861eWO5D.7wJBtkhcv3GwrwrKskc75_Jdh9vHLiDWD3xma5eXdnTYq5PANplHLfLtw.ri7UUA==");
			
			// open the connection for mutli-part POST for the first chunk
	                HttpURLConnection httpConnection = (HttpURLConnection) new URL (tokenUrl).openConnection ();
                        httpConnection.setRequestMethod ("POST");
		        httpConnection.setConnectTimeout (300000); //300s = 5mins
		        httpConnection.setReadTimeout (300000); //300s = 5mins
		
		        httpConnection.setDoInput (true);
		        httpConnection.setDoOutput (true);
	                httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	                httpConnection.setRequestProperty("Accept", "*/*");
	        
	                dos = new DataOutputStream(httpConnection.getOutputStream());
	                dos.writeBytes(sb.toString());
	                dos.flush();
	        
			StringBuffer responseBuffer = StreamUtils.gatherStream(httpConnection.getInputStream());
			System.out.println("SFDC replied access token: " + responseBuffer.toString());
	        
		} catch (Exception e) {
			String msg = "Failed to get access token when executing....";
		} finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }

            if (dos != null) {
                // close the stream
                try {
		    dos.close();
		} catch (IOException e) {
		    // NOTHING TO DO
		}
            }
        }

Also i really appreciate it if you can help me this out.

 

Thanks,

Michael

Hi,

 

i followed the instruction in http://wiki.developerforce.com/index.php/Digging_Deeper_into_OAuth_2.0_on_Force.com to get refresh_code. I tried two approached. First is in rails code, the other is in a self-submitted html form. The first leads to the second approach because it fails.

 

I don't know what's wrong with the codes in rails that leads to the failure. I really appreciate it if you can help me out.

 

Following are ruby codes to make authorization code request. It returns "{"error":"unsupported_grant_type","error_description":"grant type not supported"}"

 

oauth_url = URI.parse('https://login.salesforce.com/services/oauth2/token')
          
    http = Net::HTTP.new(oauth_url.host, oauth_url.port)
    http.use_ssl = (oauth_url.scheme == 'https')
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    
    req = Net::HTTP::Post.new('https://login.salesforce.com/services/oauth2/token')
    req["Accept"] = '*/*'
    req.content_type = "text/html"
    form_data = {'code' => 'sfdc generated code...', 'grant_type' => 'authorization_code', 'client_id' => "my client id", 'client_secret' =>  "my client secret", 'redirect_uri' => "https://localhost/sfdc/oauth_callback"}
        
    req.set_form_data(form_data, ';')
    
    begin
      logger.info "Make request: #{req.path}"
      response = Timeout::timeout(10){
        http.start do
          http.request req
        end
      }
    rescue Exception => e
      logger.error "make_http_request:  request failed: #{e}"        
      #return issue_http_request(req, tries + 1)
    end
    
    puts response.body

 

Following is the resulf from the self-submitted form.

<html><body onload="document.forms[0].submit()"><p><script language="javascript">document.write("Please wait ...");</script></p>
<noscript><p>Note: Your browser does not support JavaScript or it is turned off. Press the button to proceed.</p></noscript>
<form method="post" action="https://login.salesforce.com/services/oauth2/token">
<input type="hidden" name="code" value="sfdc generated code..."/><input type="hidden" name="grant_type" value="authorization_code"/>
<input type="hidden" name="client_id" value="my client id"/>
<input type="hidden" name="client_secret" value="my client secret"/>
<input type="hidden" name="redirect_uri" value="https://localhost/sfdc/oauth_callback"/><noscript>
<input type="submit" value="Continue"/></noscript></form></body></html>

 

{
    "id":"https://login.salesforce.com/id/00D50000000IZ3ZEAW/00550000001fg5OAAQ",
    "issued_at":"1296458209517",
   "refresh_token":"5Aep862eWO5D.7wJBuW5aaARbbxQ8hssCnY1dw3qi59o1du7ob.lp23ba_3jMRnbFNT5R8X2GUKNA==",
    "instance_url":"https://na1.salesforce.com",
    "signature":"0/1Ldval/TIPf2tTgTKUAxRy44VwEJ7ffsFLMWFcNoA=",
   "access_token":"00D50000000IZ3Z!AQ0AQDpEDKYsn7ioKug2aSmgCjgrPjG9eRLza8jXWoW7uA90V39rvQaIy1FGxjFHN1ZtusBGljncdEi8eRiuit1QdQ1Z2KSV"
}

 

Thanks,

Michael

Hi,

 

I'm using Partner WSDL API v21. I need to connect to SFDC for various SFDC users, and i think using username/password is not the best way to obtan SFDC connection through Partner WSDL API. I'm wondering if I can use OAuth in this case. By far I can get SFDC users' instance_url, client_id, client_secret and refresh_token. What I like to use OAuth in this scenario is send a request to user's instance_url to get a refreshed access token, and use the latest access token to access user's resources.

 

Would it work in this way by using Partner WSDL API wih OAuth? If so, can you post some sample codes?

 

Thanks,

Michael

Hi,

 

After reading this wiki page http://wiki.developerforce.com/index.php/Digging_Deeper_into_OAuth_2.0_on_Force.com, i tried obtaining an Access Token in a Native Application / User-Agent Flow. I would expect in the end the refresh token  will be in the redirect returned (3) containing several parameters in a URL fragment. However it doesn't include the refresh token.

 

Following are what i tried in a browser, and its redirect from Salesforce.

 

  1. Request to Salesforce: https://login.salesforce.com/services/oauth2/authorize?response_type=token&oauth_consumer_key=3MVG9Km_cBLhsuPy92UAudTyfc9ka4dxuV.OMS5r0vyIS_ThDWpVFBpenmEEUGIHUrBCeHC28ZqbFDWkcCUAd&redirect_uri=https://localhost/sfdc_callback&display=touch&state=my_value
  2. Redirect from Salesforce: https://localhost/sfdc_callback#access_token=00D500000006tTs%21AREAQKZDxGeWrnBL4rohFjDM41hdv5crgBeGDFOHx1X0rwHECCVMuBtrwAnanilp57ZSEaPHCiuQvYTftXsuYXY7XfC9dA_5&instance_url=https%3A%2F%2Fna3.salesforce.com&id=https%3A%2F%2Flogin.salesforce.com%2Fid%2F00D500000006tTsEAI%2F00550000000lo9gAAA&issued_at=1309501094987&signature=jz0mFh6LDgw9btPuGBF%2FW46eG22QTRj%2FRVT7bGEMrTo%3D&state=my_value

You can see refresh_token is not in the url. Did I miss anything? Please help on this.

 

Thanks in advance.

 

 

Hi,

 

Does Salesforce support setting up a Remote Access Application through an API rather than GUI?

 

Thanks,

Michael

Hi Simon,

 

I'd like to get Salesforce Report data with access token. I used HttpClient to setup connection to Salesforce and send request to get report data. In request header, I used cookies and add 'sid' to it. It works well. However, when I switch to OAuth it doesn't work since then. I tried assigning access token to 'sid' as well as removing 'sid' from header and adding 'Authorization: OAuth #access token#' to header of the request without success. The response code is 200 though. The response is a page with redirect to 'https://login.salesforce.com/?ec=302&startURL=/00O50000002HVb2?isExcel=1&xf=csv&export=1&enc=UTF-8'. Following are the codes for sending the request.

                GetMethod get = new GetMethod(url);
		get.setFollowRedirects(true);
		
		get.setRequestHeader("Cookie", "com.salesforce.LocaleInfo=us; inst=APP7");
		get.setRequestHeader("Authorization: OAuth ", accessToken);
		
		int iCode = client.executeMethod(get);

 Please help take a look, and help to point out what could be wrong.

 

Thanks,

Michael

Hi,

 

As I posted in this thread: http://boards.developerforce.com/t5/Security/Using-Partner-WSDL-API-with-OAuth/td-p/302435, Simon mentioned I just need to replace sessionId with access token in the SessionHeader. When i set property to binding in binding._setProperty(SoapBindingStub.ENDPOINT_ADDRESS_PROPERTY, service_url);, what url should I use here? Before I use "https://www.salesforce.com/services/Soap/u/21.0". With OAuth, I have instance_url as "https://na3.salesforce.com" for one user. Should I use this instance_url instead of previous soap url?

 

Thanks,

Michael

Hi,

 

Here is another similar situation, but this time I tried to request for access token with refresh_token in Java. I got error "java.io.IOException: Server returned HTTP response code: 400 for URL: https://login.salesforce.com/services/oauth2/token". It works if I use a self-submitted html form to get access token from Salesforce.

 

Here is the Java codes for the request:

                String tokenUrl = "https://login.salesforce.com/services/oauth2/token";
		HttpURLConnection httpConnection = null;
		DataOutputStream dos = null;
		
		try{
			StringBuilder sb = new StringBuilder("grant_type=refresh_token");
			sb.append("&client_id=").append("3MVG9Km_cBLhsuPy92UAudTyfc9ka4dxuV.OMS5r0vyIS_ThDWpVFBpenmEEUGIHUrBCeHC28ZqbFDWkcCUAd");
			sb.append("&client_secret=").append("7408566340993550860");
			sb.append("&refresh_token=").append("5Aep861eWO5D.7wJBtkhcv3GwrwrKskc75_Jdh9vHLiDWD3xma5eXdnTYq5PANplHLfLtw.ri7UUA==");
			
			// open the connection for mutli-part POST for the first chunk
	                HttpURLConnection httpConnection = (HttpURLConnection) new URL (tokenUrl).openConnection ();
                        httpConnection.setRequestMethod ("POST");
		        httpConnection.setConnectTimeout (300000); //300s = 5mins
		        httpConnection.setReadTimeout (300000); //300s = 5mins
		
		        httpConnection.setDoInput (true);
		        httpConnection.setDoOutput (true);
	                httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	                httpConnection.setRequestProperty("Accept", "*/*");
	        
	                dos = new DataOutputStream(httpConnection.getOutputStream());
	                dos.writeBytes(sb.toString());
	                dos.flush();
	        
			StringBuffer responseBuffer = StreamUtils.gatherStream(httpConnection.getInputStream());
			System.out.println("SFDC replied access token: " + responseBuffer.toString());
	        
		} catch (Exception e) {
			String msg = "Failed to get access token when executing....";
		} finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }

            if (dos != null) {
                // close the stream
                try {
		    dos.close();
		} catch (IOException e) {
		    // NOTHING TO DO
		}
            }
        }

Also i really appreciate it if you can help me this out.

 

Thanks,

Michael

Hi,

 

i followed the instruction in http://wiki.developerforce.com/index.php/Digging_Deeper_into_OAuth_2.0_on_Force.com to get refresh_code. I tried two approached. First is in rails code, the other is in a self-submitted html form. The first leads to the second approach because it fails.

 

I don't know what's wrong with the codes in rails that leads to the failure. I really appreciate it if you can help me out.

 

Following are ruby codes to make authorization code request. It returns "{"error":"unsupported_grant_type","error_description":"grant type not supported"}"

 

oauth_url = URI.parse('https://login.salesforce.com/services/oauth2/token')
          
    http = Net::HTTP.new(oauth_url.host, oauth_url.port)
    http.use_ssl = (oauth_url.scheme == 'https')
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    
    req = Net::HTTP::Post.new('https://login.salesforce.com/services/oauth2/token')
    req["Accept"] = '*/*'
    req.content_type = "text/html"
    form_data = {'code' => 'sfdc generated code...', 'grant_type' => 'authorization_code', 'client_id' => "my client id", 'client_secret' =>  "my client secret", 'redirect_uri' => "https://localhost/sfdc/oauth_callback"}
        
    req.set_form_data(form_data, ';')
    
    begin
      logger.info "Make request: #{req.path}"
      response = Timeout::timeout(10){
        http.start do
          http.request req
        end
      }
    rescue Exception => e
      logger.error "make_http_request:  request failed: #{e}"        
      #return issue_http_request(req, tries + 1)
    end
    
    puts response.body

 

Following is the resulf from the self-submitted form.

<html><body onload="document.forms[0].submit()"><p><script language="javascript">document.write("Please wait ...");</script></p>
<noscript><p>Note: Your browser does not support JavaScript or it is turned off. Press the button to proceed.</p></noscript>
<form method="post" action="https://login.salesforce.com/services/oauth2/token">
<input type="hidden" name="code" value="sfdc generated code..."/><input type="hidden" name="grant_type" value="authorization_code"/>
<input type="hidden" name="client_id" value="my client id"/>
<input type="hidden" name="client_secret" value="my client secret"/>
<input type="hidden" name="redirect_uri" value="https://localhost/sfdc/oauth_callback"/><noscript>
<input type="submit" value="Continue"/></noscript></form></body></html>

 

{
    "id":"https://login.salesforce.com/id/00D50000000IZ3ZEAW/00550000001fg5OAAQ",
    "issued_at":"1296458209517",
   "refresh_token":"5Aep862eWO5D.7wJBuW5aaARbbxQ8hssCnY1dw3qi59o1du7ob.lp23ba_3jMRnbFNT5R8X2GUKNA==",
    "instance_url":"https://na1.salesforce.com",
    "signature":"0/1Ldval/TIPf2tTgTKUAxRy44VwEJ7ffsFLMWFcNoA=",
   "access_token":"00D50000000IZ3Z!AQ0AQDpEDKYsn7ioKug2aSmgCjgrPjG9eRLza8jXWoW7uA90V39rvQaIy1FGxjFHN1ZtusBGljncdEi8eRiuit1QdQ1Z2KSV"
}

 

Thanks,

Michael

Hi,

 

I'm using Partner WSDL API v21. I need to connect to SFDC for various SFDC users, and i think using username/password is not the best way to obtan SFDC connection through Partner WSDL API. I'm wondering if I can use OAuth in this case. By far I can get SFDC users' instance_url, client_id, client_secret and refresh_token. What I like to use OAuth in this scenario is send a request to user's instance_url to get a refreshed access token, and use the latest access token to access user's resources.

 

Would it work in this way by using Partner WSDL API wih OAuth? If so, can you post some sample codes?

 

Thanks,

Michael