com.dropbox.core.DbxException$BadRequest: {"error": "OAuth 2 \"Authorization\" header is not well-formed."} - dropbox-api

I am getting following exception on uploading file to dropbox using java api.
com.dropbox.core.DbxException$BadRequest: {"error": "OAuth 2 \"Authorization\" header is not well-formed."}
at com.dropbox.core.DbxRequestUtil.unexpectedStatus(DbxRequestUtil.java:207)
at com.dropbox.core.DbxClient$SingleUploader$1.handle(DbxClient.java:765)
at com.dropbox.core.DbxClient$SingleUploader$1.handle(DbxClient.java:761)
at com.dropbox.core.DbxRequestUtil.finishResponse(DbxRequestUtil.java:279)
at com.dropbox.core.DbxClient$SingleUploader.finish(DbxClient.java:761)
at com.dropbox.core.DbxClient.finishUploadFile(DbxClient.java:629)
at com.dropbox.core.DbxClient.uploadFile(DbxClient.java:562)
at com.dropbox.core.DbxClient.uploadFile(DbxClient.java:514)
following is my code
public DbxClient authDropbox(String authAccessToken)throws IOException, DbxException {
DbxRequestConfig dbxRequestConfig = new DbxRequestConfig("JavaDropboxTutorial/1.0", Locale.getDefault().toString());
dbxClient = new DbxClient(dbxRequestConfig, authAccessToken);
return dbxClient;
}
public String uploadToDropbox(String filePath,String fileName,String folderName,DbxClient dbxClient) throws DbxException,IOException {
String sharedUrl;
File inputFile = new File(filePath);
FileInputStream fis = new FileInputStream(inputFile);
try {
dbxClient.uploadFile("/"+folderName+"/"+ fileName,DbxWriteMode.add(), inputFile.length(), fis);
sharedUrl = dbxClient.createShareableUrl("/"+folderName +"/"+fileName);
} finally {
fis.close();
}
return sharedUrl;
}
file upload code

The error 'OAuth 2 "Authorization" header is not well-formed.' indicates that the header that contains the OAuth 2 access token doesn't match the pattern expected for the header.
The header is built for you by the SDK using the accessToken parameter you supply to the DbxClient constructor, which in your case is your authAccessToken variable.
That likely means that the value of your authAccessToken isn't a valid access token, and whatever string it does contain is causing the header to not match the pattern. For example, it might contain whitespace, which could cause this.
To fix this, you should inspect the value of your authAccessToken and see what's in it and why it's malformed, and prevent that from happening again in the future.

Related

C#.Net RestSharp client - passing auth token

I am writing a REST client in C#.Net using RestSharp. There are two API calls - one is "Auth" call and second is "getKey" call. The "Auth" call throws back a "Auth token"in the response, and I'd like to parse that token from the response, and pass it as an header to the second "getkey" call. Please advise with examples
I have given some sample to achieve your scenario. Please use the below example and do the modification as per your requirement.
RestUtils Class:
Add the Request Header, If your application is expected some additional headers.
class RestUtils
{
private static readonly RestClient _restClient = new RestClient();
public static void SetBaseURL(String host)
{
_restClient.BaseUrl = new Uri(host);
}
public static string GetResponse(String endpoint, String token)
{
var request = new RestRequest(endpoint, Method.GET);
request.AddHeader("Accept", "application/json");
request.AddHeader("Authorization", token);
IRestResponse response = _restClient.Execute(request);
return response.Content;
}
public static string GetToken(String endpoint)
{
var request = new RestRequest(endpoint, Method.GET);
request.AddHeader("Accept", "application/json");
IRestResponse response = _restClient.Execute(request);
return response.Content;
}
}
TestClass:
In your test class you can add the below steps and you can get the result as expected. First two lines will be executed and give the authentication token as output. So, you can use the retrieved token in the subsequent lines for other API. In another way, you can create one property class and set the retrieved token value .So, that you can access the token from various class.
//Specify the Base URI of your Token Specific API
RestUtils.SetBaseURL("https://login.microsoftonline.com/");
//Specify the End Point of your Token Specific API
String token = RestUtils.GetToken("/oauth2/token");
//Specify the Base URI of your actual Test API
RestUtils.SetBaseURL("XXXXXXX");
String response = RestUtils.GetResponse(token);

I am trying to update status to twitter using twitter4j but it does not work

I succeeded to get every credentials(Oauth_token,Oauth_verifier).
With it, I tried to post a text to twitter account, but it always fail with error message "No authentication challenges found"
I found some solution like
"Check the time zone automatically",
"import latest twitter4j library" etc..
but after check it, still not work.
Is there anyone can show me the way.
code is like below
public static void updateStatus(final String pOauth_token,final String pOauth_verifier) {
new Thread() {
public void run() {
Looper.prepare();
try {
TwitterFactory factory = new TwitterFactory();
AccessToken accessToken = new AccessToken(pOauth_token,pOauth_verifier);
Twitter twitter = factory.getInstance();
twitter.setOAuthConsumer(Cdef.consumerKey, Cdef.consumerSecret);
twitter.setOAuthAccessToken(accessToken);
if (twitter.getAuthorization().isEnabled()) {
Log.e("btnTwSend","인증값을 셋팅하였고 API를 호출합니다.");
Status status = twitter.updateStatus(Cdef.sendText + " #" + String.valueOf(System.currentTimeMillis()));
Log.e("btnTwSend","status:" + status.getText());
}
} catch (Exception e) {
Log.e("btnTwSend",e.toString());
}
};
}.start();
}
"No authentication challenges found"
I think you are missing Access token secret in your code. That is why you are getting this exception.
Try following :
ConfigurationBuilder configurationBuilder;
Configuration configuration;
// Set the proper configuration parameters
configurationBuilder = new ConfigurationBuilder();
configurationBuilder
.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
configurationBuilder
.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access token
configurationBuilder.setOAuthAccessToken(ACCESS_TOKEN);
// Access token secret
configurationBuilder
.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
// Get the configuration object based on the params
configuration = configurationBuilder.build();
// Pass it to twitter factory to get the proprt twitter instance.
twitterFactory = new TwitterFactory(configuration);
twitter = twitterFactory.getInstance();
// use this instance to update
twitter.updateStatus("Your status");
I finally found the reason.
I thought parameter named 'oauth_token' , 'oauth_verifier' is member of accesstoken,
but it was not true.
I just had to pass one more way to get correct key.
and this way needs 'oauth_token' , 'oauth_verifier' to get accesstoken.
This code must add one more code below:
mAccessToken = mTwitter.getOAuthAccessToken(REQUEST_TOKEN,OAUTH_VERIFIER);

504 error accessing Kinvey handshake(Rest api)

I have been trying to get the Kinvey handshake for the REST api to work for a while now but have not had any luck. I am using libgdx's net class to send the http request. Wverytime I send the request I get a 504(Gateway Timeout) error. I am following the instructions on the website so I am not sure why I would get that error.
Here is my attempt:
HttpRequest request = new HttpRequest(HttpMethods.GET);
request.setHeader("GET", "/appdata/:App_key");
request.setHeader("Host:", "baas.kinvey.com");
String authHeader = "Basic " + Base64Coder.encodeString("App_key:App_secret");
request.setHeader("Authorization:", authHeader);
request.setUrl("https://baas.kinvey.com/appdata/App_key");
System.out.println("HTTP REQUEST: " + request.getHeaders());
responseListener listener = new responseListener() {
public void handleHttpResponse (HttpResponse httpResponse) {
HttpStatus status = httpResponse.getStatus();
if (status.getStatusCode() >= 200 && status.getStatusCode() < 300) {
System.out.println("HTTP SUCCESS!");
} else {
System.out.println("HTTP ERROR: " + status.getStatusCode());
}
System.out.println("HTTP :" + httpResponse.getResultAsString());
}
#Override
public void failed(Throwable t) {
t.printStackTrace();
System.out.println("REQUEST FAILED!" +t.getMessage());
super.failed(t);
}
};
Gdx.net.sendHttpRequest(request, listener);
As far as I can tell, there is something wrong with the header. I have tested the Url which takes me to a login screen. The login works after I put in the App key as the user name and the Master secret as the password. Is there something obviously wrong? Is there a way I can debug this further?
I'm an engineer at Kinvey and can help you out with this.
A couple things:
first, there are some extra headers there that you don't need. While they might not be the cause of the issue, it is still safe to remove:
request.setHeader("GET", "/appdata/:App_key");
request.setHeader("Host:", "baas.kinvey.com");
Note that GET is set when you create the HttpRequest, and Host is set when you define the URL.
Second, get rid of the colon after "authorization" when setting your header, make it look like this:
request.setHeader("Authorization", authHeader);
Also, you mention that it works with your master secret but not with your app secret? Can you ensure that you are base64 encoding both?
One last thing-- ensure that you replace App_Key with your actual app key, in the URL as well as in the headers.

facebook Access Token 400 bad request

I am using following code to retrieve facebook accessToken
string url = "https://graph.facebook.com/oauth/access_token?" +
"client_id={0}" +
"&redirect_uri={1}" +
"&client_secret={2}" +
"&code={3}";
url = string.Format(url, clientId, redirectUri.EncodeUrl(), clientSecret, code);
//Create a webrequest to perform the request against the Uri
WebRequest request = WebRequest.Create(url);
try
{
//read out the response as a utf-8 encoding and parse out the access_token
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
//string urlRedirects = response.ResponseUri.ToString();
Encoding encode = Encoding.GetEncoding("utf-8");
if (stream != null)
{
StreamReader streamReader = new StreamReader(stream, encode);
string accessToken = streamReader.ReadToEnd().Replace("access_token=", "");
streamReader.Close();
response.Close();
return accessToken;
}
}
}
}
catch
{
return null;
}
however I am constantly receiving this ambiguous error message
{
"error": {
"message": "Error validating verification code.",
"type": "OAuthException",
"code": 100
}
}
I checked the code 100 "Invalid parameter" doesn't means much to me at all.
anyone have had similar problem?
Check you are adding correct code in the url
For example
http://www.xyz.com/?code=AQC399oXame3UKmoAMYnqkZOEXPDNa8ZUFEY9sc6I4YNQnNT-ZgHzpMNnQVZrCUBZVqJRIB1QrXC5xW58_8MNIgQol_PaQvYssUM8OiKjSY5aoqGLBMuCeeHsSqP_mRTd1xiK0iretZcXwMm_27lFYrWFw345Mxod_lfJuB8zI13E8wJUQiArXW_ZlGLNcyxh20#_=_
Code must be
code = AQC399oXame3UKmoAMYnqkZOEXPDNa8ZUFEY9sc6I4YNQnNT-ZgHzpMNnQVZrCUBZVqJRIB1QrXC5xW58_8MNIgQol_PaQvYssUM8OiKjSY5aoqGLBMuCeeHsSqP_mRTd1xiK0iretZcXwMm_27lFYrWFw345Mxod_lfJuB8zI13E8wJUQiArXW_ZlGLNcyxh20
code should not include following in the end
#_=_
If above did not solve the problem
2. redirect_uri must end with /
redirect_uri=http://www.xyz.com/
The following gives some times above mentioned error
redirect_uri=http://www.xyz.com
3. A lso make sure
App on Facebook and Website with Facebook Login are set with same addresss
e.g http://www.xyz.com/
You need to send the user to the Facebook Login page to get a valid code. The code should then be used to get the access_token for the user.
Follow the Authentication Guide.
I also got error message 400, when my app id and secret were wrong (i had messed up develop and production id-s and secrets).
Fixing them (watch also out for the correct host) fixed this problem for me.

How To URLEncode Facebook Post Data in C#

I am rewriting code from http://blog.blackballsoftware.com/2010/11/03/making-a-facebook-wall-post-using-the-new-graph-api-and-c/ to create a class to post to Facebook. The code works as long as I do not URLEncode the post data. For example: If the post data is "message=Test,please ignore" then it works. If I URLEncode the same data into "message%3dTest%2cplease+ignore" then I get the error {"error":{"message":"(#100) Missing message or attachment","type":"OAuthException","code":100}}.
Should the Post data be URLEncoded? I think it should because if I post a message like this, "Test&Message", then only the word Test appears.
Relevant code is below. If postParams = HttpUtility.UrlEncode(postParams); is commented out, then the code works. If not, Facebook returns the error that the message is missing.
postParams = HttpUtility.UrlEncode(postParams);
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postParams);
webRequest.ContentLength = bytes.Length;
System.IO.Stream os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
try
{
var webResponse = webRequest.GetResponse();
}
catch (WebException ex)
{
StreamReader errorStream = null;
errorStream = new StreamReader(ex.Response.GetResponseStream());
error = errorStream.ReadToEnd() + postParams;
}
The answer can be found on Stackoverflow at C# Escape Plus Sign (+) in POST using HttpWebRequest. Use Uri.EscapeDataString and not URLEncode. Encode the parameter value only and not the equals sign after the parameter name. Example: message=Test%2Cplease%26%20ignore works but message%3dTest%2Cplease%26%20ignore does not work because the equals after the parameter name is encoded as %3d.