Salesforce Oauth Status Code 302 - salesforce

While trying to setup oauth in the org, getting status code 302.
Below is the code snippet.
String AUTH_URL = 'https://login.salesforce.com/services/oauth2/authorize';
String redirect_uri = 'https://login.salesforce.com/services/oauth2/success';
String response_type = 'token';
String client_id = 'xxxxxxxxxxxxxx.xxxxxxxxx';
authURL = AUTH_URL +
'?response_type=' + response_type +
'&client_id=' + client_id +
'&redirect_uri=' + redirect_uri;
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setMethod('GET');
req.setEndpoint(authUrl);
res = http.send(req);
//RESULT:
res.getStatusCode() = 302
res.getStatus() = Found
I am expecting to receive access Token and refresh token in response's body but it is empty.
Please suggest if I am missing out on something.
Thanks in advance.

the authorize endpoint is for a browser based interactive login, not a programatic login. If you want a pure programatic method, then you should checkout the username/password oauth flow that you can use via the /services/oauth2/token endpoint.

Related

OKTA Invalid Scope issue s

I am trying to use OKTa for APP to APP authentication inside a SpringBoot Application and I get the below Scope issues ,
org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad
Request: [{"error":"invalid_scope","error_description":"One or more scopes
are not configured for the authorization server resource."}]
we have default custome_scope mentioned at the Okta sever and when I try using the below code I am getting error while accesing line no 5 : in the below code snippet ,
String tokenUri = issuerUri + "/v2/token" + "? grant_type=client_credentials&response_type=token&scope=read";
RestTemplate rt = new RestTemplate();
headers = setHeaders(clientId, clientSecret, headers);
HttpEntity requestEntity = new HttpEntity(headers);
TokenData response = rt.postForObject(tokenUri, requestEntity, TokenData.class);
Can anyone help me

How to send Twilio SMS via Web Service in Salesforce Apex

I want to send SMS from Twilio noticed they have libraries built for Java, .Net, Node, etc. so that we can use them if we are upto those technologies.
But I want to do the same from Salesforce Apex and trying to figure out how to build the Http parameters to make the authorization.
I tried to map with cURL example given in Twilio documentation and can't find header keys for Auth token.
Below is my current code and looking for how to set the authentication params.
req.setEndpoint(baseURL + '/2010-04-01/Accounts/account_sid/Messages.json');
req.setMethod('POST');
req.setHeader('to', EncodingUtil.urlEncode('+to_number', 'UTF-8'));
req.setHeader('from', EncodingUtil.urlEncode('+from_number', 'UTF-8'));
Http ht = new Http();
HttpResponse res = ht.send(req);
Updated request :
Blob headerValue = Blob.valueOf('my-twilio-account-sid:my-twilio-auth-token');
String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
String body = EncodingUtil.urlEncode('From=+from_number&To=+to_number&Body=Sample text from twilio', 'UTF-8');
req.setBody(body);
Http ht = new Http();
HttpResponse res = ht.send(req);
Response saying
Bad Request : A 'From' phone number is required.
The phone numbers don't go in the headers.
For the headers you will need
Content-Type: "application/x-www-form-urlencoded"
then you will need another header for authorization
Authorization: auth-string
where auth-string is a combination of the string Basic followed by a space followed by a base64 encoding of twilio-account-sid:twilio-auth-token (replace with your Twilio credentials joined by the colon) so the header will look something like
Authorization: "Basic ABCiDEdmFGHmIJKjLMN2OPQwR2S3TUVzABliCDE3FGc1HIo2JKL2MjNwOPcxQRSwTUc1Vzc0XmYhZAB3CDElFGH1Jw=="
The body of the POST request should contain key, value pairs of To, From and Body, something like
"From=" + twilio-phone-number + "&To=" + to-number + "&Body=" + message-body (replace with string values for phone numbers and message).
I hope this helps.

error_type":"OAuthAccessTokenException","code":400,.. (instagram)

I am accessing the instagram API to display content from a specific account, however I get this error:
/**/ JSON_CALLBACK({"meta":{"error_type":"OAuthAccessTokenException","code":400,"error_message":"The access_token provided is invalid."}})
I have registered my app in https://www.instagram.com/developer/
bit when accessing here for example I get that above error:
var endpoint = "https://api.instagram.com/v1/users/" + user_id + "/media/recent/?";
endpoint += "?count=99";
endpoint += "&client_id=" + client_id;
endpoint += "&callback=JSON_CALLBACK";
You cannot access this API with client_id anymore, you have to authenticate, get an access_token and make API call with access_token, see documentation for this endpoint here:
https://www.instagram.com/developer/endpoints/users/#get_users_media_recent

SalesForce Apex code fails on file download - Premature EOF

In my Apex code, I am trying to download a remote csv file to process in-memory. Unfortunately, I am getting a System.CalloutException: Premature EOF error when I try to get the file. I am able to connect to the server with the file (I can see the error messages returned when the file is not ready for download) so the connection details are likely not the problem.
private static void processURL(String url, UserHelper__c helper){
String username = 'login';
String password = 'password';
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint(url);
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);
req.setMethod('GET');
try {
System.debug('processURL Send request: '+req);
res = http.send(req); //Premature EOF hits here.
System.debug('processURL successful');
} catch(System.CalloutException e) {
System.debug('processURL error: '+ e);
}
...
}
This was caused by the server sending its response in a buffered manner. It seems that the SalesForce Apex code cannot handle a buffered response. I don't have all the details on what happened on the server-side so I cannot give more details than that.

AppEngine - Send files to the blobstore using HTTP

I'm trying to send files to the blobstore using http requests.
First I made a button to call the createUploadUrl to get the upload url.
Then I made a client:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL_FROM_CREATEUPLOADURL);
httpPost.setEntity(new StringEntity("value1"));
HttpResponse httpResponse = httpClient.execute(httpPost);
But I have 2 problems:
In dev mode: When I run the client it responses "Must call one of set*BlobStorage() first."
If I upload the app: The url changes every time I call it, so when I run the client it responses "HTTP/1.1 500 Internal Server Error"
What I'm doing wrong?
It sounds like you're trying to hard-code a single upload URL. You can't do that - you need to generate a new one for each file you want to upload.
You also need to make sure that you upload the file as a multipart message rather than using formencoding or a raw body. I'm not familiar with the Java APIs, but it looks like you're setting the raw body of the request.
apparently the entity must be a MultiPartEntity.
This is the client code to get the URL:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myDomain/mayServlet);
HttpResponse httpResponse = httpClient.execute(httpPost);
Header[] headers = httpResponse.getHeaders(myHeader);
for (int i = 0; i < headers.length; i++) {
Header header = headers[i];
if(header.getName().equals(myHeader))
uploadUrl = header.getValue();
This is the server code to return the URL:
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String uploadUrl = blobstoreService.createUploadUrl(requestHandlerServlet);
resp.addHeader("uploadUrl", uploadUrl);
This is the client upload code:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uploadUrl);
MultipartEntity httpEntity = new MultipartEntity();
ContentBody contentBody = new FileBody(new File("filePath/fileName"));
httpEntity.addPart("fileKey", contentBody);
httpPost.setEntity(httpEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
so easy... :(

Resources