Missing parameter access_token on OAuth2 request - android

I'm using the Apache Amber libraries to try to retrieve an OAuth2 access token from a Web site under my control. My client code is running under Android.
My code is patterned on the example at:
https://cwiki.apache.org/confluence/display/AMBER/OAuth+2.0+Client+Quickstart
In the first step, I'm able to retrieve a "code" by submitting a GET request using a WebView browser:
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation(AUTHORIZE_URL)
.setClientId(CLIENT_ID)
.setRedirectURI(REDIR_URL)
.setResponseType(CODE_RESPONSE)
.buildQueryMessage();
webview.loadUrl(request.getLocationUri());
I use a WebViewClient callback to capture the redirect URL with the "code" parameter. So far, so good.
Using that code, I try to retrieve my access token:
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthClientRequest request = OAuthClientRequest
.tokenLocation(ACCESS_TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setRedirectURI(REDIR_URL)
.setCode(code)
.buildBodyMessage();
GitHubTokenResponse oAuthResponse =
oAuthClient.accessToken(request, GitHubTokenResponse.class);
Each time I run my code, I get an OAuthProblemException, where the message is that I have an invalid request due to a missing parameter, access_token.
Another StackOverflow post mentions this exception from a similar OAuth2 request, which in that case was caused by having different redirect URIs across OAuth requests. But I've made sure my redirect URIs are the same by using a named constant. Here's the link to that post:
OAuthProblem, missing parameter access_token
Now, I can print out the code returned by the first request, and paste it into a curl command run from my desktop machine:
curl -d "code=...&client_id=...&client_secret=...&grant_type=...&redirect_uri=..." http://my_website.com
and I get a nice JSON response from my site with an access_token.
Why does the call from Java fail, where my hand-rolled command line succeeds?

I had the same problem implementing the client and the server, the problem is about one mistake in the Client Example in the Apache Amber (Oltu) project:
First you have the Auth code request (which work):
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation(AUTHORIZE_URL)
.setClientId(CLIENT_ID)
.setRedirectURI(REDIR_URL)
.setResponseType(CODE_RESPONSE)
.**buildQueryMessage**();
And second the request about the Access Token (which don't work):
OAuthClientRequest request = OAuthClientRequest
.tokenLocation(ACCESS_TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setRedirectURI(REDIR_URL)
.setCode(code)
.**buildBodyMessage**();
The mistake is about the buildBodyMessage() in the second request. Change it by buildQueryMessage().

Solved in my case.
Amber/Oltu "Missing parameter access_token" error may mean that GitHubTokenResponse or OAuthJSONAccessTokenResponse are unabled to translate response body for any reason. In my case (with Google+ oAuth2 authentication), the response body, is not parsed properly to the inner parameters map.
For example:
GitHubTokenResponse
parameters = OAuthUtils.decodeForm(body);
Parse a form-urlencoded result body
... and OAuthJSONAccessTokenResponse has the next parse function
parameters = JSONUtils.parseJSON(body);
This JSONUtils.parseJSON is a custom JSON parser that not allow for me JSON response body from GOOGLE+ and throws an JSONError (console not logged),
Each error throwed parsing this parameters, are not console visible, and then always is throwed doomed "Missing parameter: access_token" or another "missing parameter" error.
If you write your Custom OAuthAccessTokenResponse, you can see response body, and write a parser that works with your response.

This is what I encountered and what I did to get it working:
I quickly put together a similar example described in:
https://cwiki.apache.org/confluence/display/OLTU/OAuth+2.0+Client+Quickstart
and:
svn.apache.org/repos/asf/oltu/trunk/oauth-2.0/client/src/test/java/org/apache/oltu/oauth2/client/OAuthClientTest.java
This was my command to execute it:
java -cp .:./org.apache.oltu.oauth2.client-1.0.1-20150221.171248-36.jar OAuthClientTest
I also ended up with the above mentioned error where the access_token was expected. I ended up debugging in intellij and traced an anomaly with the if condition which checks that the string begins with the "{" character.
In doing so, I also added the following jar to my classpath so that I may debug the trace a little deeper.
./java-json.jar
(downloaded from http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm)
During the next debug session, the code actually started working. My mate and I eventually found the root cause was due to the JSON jar not being included.
This is the command which works:
java -cp .:./java-json.jar:./org.apache.oltu.oauth2.client-1.0.1-20150221.171248-36.jar OAuthClientTest

I was having the same problem when trying to get the access token from fitbit OAuth2. buildBodyMessage() and buildQueryMessage() were both giving me missing parameter, access_token.
I believe this is something to do with the apache oauth2 client library. I ended up making simple post requests using spring's RestTemplate and it's working fine.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.set("Authorization", "Basic " + "MjI5TkRZOjAwNDBhNDBkMjRmZTA0OTJhNTE5NzU5NmQ1N2ZmZGEw");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("client_id", FITBIT_CLIENT_ID);
map.add("grant_type", "authorization_code");
map.add("redirect_uri", Constants.RESTFUL_PATH + "/fitbit/fitbitredirect");
map.add("code", code);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(FITBIT_TOKEN_URI, request, String.class);
log.debug("response.body: " + response.getBody());

Related

Getting Google Play Games player ID on server

The post Play Games Permissions are changing in 2016 explains how to get the Play Games player ID on a server. I can successfully get the access token on the server, but I can't get this step to work:
Once you have the access token, call www.googleapis.com/games/v1/applications/yourAppId/verify/ using that
access token. Pass the auth token in a header as follows:
“Authorization: OAuth ” The response value will contain
the player ID for the user.
I'm trying to do that in Google App Engine using:
accessToken = ...; //-- I can always get this successfully
URL url = new URL(String.format("https://www.googleapis.com/games/v1/applications/%s/verify/",myAppId));
HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET);
HTTPHeader httpHeader = new HTTPHeader("Authorization: OAuth",accessToken);
request.addHeader(httpHeader);
HTTPResponse httpResponse = urlFetchService.fetch(request);
The response always return code 401. How can I debug?
An identical issue (sort of) indicates that you'll have to set the header differently (not using HttpHeader).
httppost.setHeader("Authorization", "Bearer "+accessToken);
Hopefully this can fix your issue.
The problem was with the header, it should be added like this:
HTTPHeader httpHeader = new HTTPHeader("Authorization","OAuth " + accessToken);

HttpMethod.Delete not working with RestTemplate of Spring-Android

I am trying to use DELETE method of HttpMethod. The code that I am using for that is
response = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, Response.class);
I am also using JacksonJson for mapping json. The delete functionality returns the json which should be mapped to Response class. But calling the above line doesn't works and gives internal server error with 500 as response code. But, the same API does work with RESTClient in the browser so I guess there is something that I am not doing correctly.
After doing some more research it seems that DELETE method doesn't supports request body. As we had the control over REST API we have changed the request body to be added as parameters. After doing this change the request is working properly.
Hope it helps someone.
A little late to the party I'd like to chime in here as well (document my solution for posterity)
I'm too using spring's rest template, also trying to perform a delete request with a payload AND i'd also like to be able to get the response code from the server side
Disclaimer: I'm on Java 7
My solution is also based on a post here on SO, basically you initially declare a POST request and add a http header to override the request method:
RestTemplate tpl = new RestTemplate();
/*
* http://bugs.java.com/view_bug.do?bug_id=7157360
* As long as we are using java 7 we cannot expect output for delete
* */
HttpHeaders headers = new HttpHeaders();
headers.add("X-HTTP-Method-Override", "DELETE");
HttpEntity<Collection<String>> request = new HttpEntity<Collection<String>>(payload, headers);
ResponseEntity<String> exchange = tpl.exchange(uri, HttpMethod.POST, request, String.class);

how to get the information from a http head in android

i've been given the task to send a POST message to the server giving it a JSON encoded message. The server would then send back a responce in a custom HTTP header field “X-SubmissionResponse”
so far i can successfully connect to the server (i know this because i get the responce code 202)
but i am having a lot of difficulty in getting the information from the responce, below is the code that i am currently using.
Error content not available
This code ends up returning null, Can anyone see what i am missing here?
This is the code above the if statement ^
Error content not available
Header name = response.getFirstHeader("X-SubmissionResponse");
String whatsInhere = "";
if (name != null)
whatsInhere = name.getValue();
Try using the correct methods of the Class Header.
See http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/Header.html
HttpHead head = new HttpHead();
creates a new HEAD request, empty, that does not do anything in itself.
You want the header from the response to your request. Get it by simply:
Header name = response.getFirstHeader("X-SubmissionResponse");

Android http post send with different charset encoding

i've got a problem do a http post on android with german "umlaute" äöü. I am passing a json object to the method below and execute the returned ClientResource with post and the request entity in the returned client response. When I want to post something like { "foo":"bär" } the HttpClient sends something like { "foo":"b√§r" }.
Don't know why. What am I doing wrong.
public static ClientResource newPostRequest(Context context, String urn,
JSONObject form) throws MissingAccessTokenException {
ClientResource resource = new ClientResource(uri + urn);
StringRepresentation sr = new StringRepresentation(form.toString());
sr.setMediaType(MediaType.APPLICATION_JSON);
resource.getRequest().setEntity(sr);
return resource;
}
Update
I used the default android http client (which is a apache http client I believe) and got the same error. So the problem might be located here. I try to implement another json parser (currently gson) and (if possible) another http client. Be back later...
Update
Gson is not the problem. I added a json String to the StringRepresentation and nothing changed.
ANSWER
Well that's an odd one. Maybe someone can clear this for me. I always asked myself, why √§ where used and I figured out that translating the utf-8 ä leads to √§. Obviously my android phone did not use macroman, but my mac did. I therefor changed the text file encoding in eclipse, restarted eclipse and the tomcat server and it worked. Still the TCP/IP Monitor in eclipse uses mac roman which looks still wrong. It was thereby a problem with my server, not with the restlet client on android. I just couldn't see it because the TCP/IP Monitor encoded everything in macroman.
did you try calling setCharacterSet(...) on your StringRepresentation? e.g.,
StringRepresentation sr = new StringRepresentation(form.toString());
sr.setCharacterSet(CharacterSet.UTF_8);

Android : 400 Error code when accessing a RESTful webservice

I want to access a Restful web service. I want the request should be in the following format.
GET /API/Contacts/username HTTP/1.1
HOST: $baseuri:port
Accept: text/xml
Authorization: Basic ZmF0aWdhYmxlIGdlbmVyYXR=
And also I am calling the web service though HTTPS protocol.
The folowing is the code I am using :
HttpGet get = new HttpGet("https://secure.myapp.com/MyApp/API/Contacts/myname");
get.addHeader("Accept","text/xml");
get.addHeader("Authorization","Basic ZmF0aWdhYmxlIGdlbmVyYXR=");
get.addHeader("Host","https://secure.myapp.com");
get.addHeader("Connection Use","HTTP 1.1");
DefaultHttpClient client = new DefaultHttpClient();
ResponseHandler objHandler = new BasicResponseHandler();
String getResponse = client.execute(get,objHandler);
But I am getting an Error : 400 Bad request.
I am not sure whether my code is correct. Is it necessary to specify the method (GET, POST or PUT) explicitly in the header?
Please help me...
Thnking You....
Shouldn't you put 'Basic ZmF0aWdhYmxlIGdlbmVyYXR=' in double quotes?
Also check web service example request and response and make sure that everything is specified.
Ohh...
That was my mistake.
I did not keep the order of adding headers.
When I changed its order according to the Request it is working fine.
In the request the HOST should be the first parameter.
The following is the corrected code.
get.addHeader("Host","secure.myapp.com");
get.addHeader("Accept","text/xml");
get.addHeader("Authorization","Basic ZmF0aWdhYmxlIGdlbmVyYXR=");
get.addHeader("Connection Use","HTTP 1.1");
Sorry to disturb you all...

Categories

Resources