The Google oauth endpoint returns a "bad request" ... but why?

After you spent a lot of time looking for possible reasons for the “unsuccessful request” when requesting a token at https://accounts.google.com/o/oauth2/token , I decided to ask why this code cannot get anything, except for the "bad request" response from the server ...

String url = "https://accounts.google.com/o/oauth2/token"; HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); con.setChunkedStreamingMode(0); con.setRequestMethod("POST"); con.setRequestProperty("Host", "accounts.google.com"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("code", authCode); con.setRequestProperty("client_id", "[CLIENT_ID]"); con.setRequestProperty("client_secret", "[CLIENT_SECRET"); con.setRequestProperty("redirect_uri", "http://localhost:8080/login"); con.setRequestProperty("grant_type", "authorization_code"); // Send post request con.setDoOutput(true); 

I had to set con.setChunkedStreamingMode(0) because the server was returning an error related to the length of the content.

Any ideas? Could it be necessary to place the payload on one line? as?

+1
source share
1 answer

I believe that the reason for HTTP 400 (Bad Request) is to send code , client_id , client_secret , grant_type and redirect_uri as HTTP request headers, where you need to send them as request parameters in the body of the HTTP POST request (according to Google OAuth2InstalledApp docs ) .

Take a look at Using java.net.URLConnection to start and process HTTP requests for a good example of sending HTTP POST. You need to take code , client_id , etc. And write them as a query string in the body:

 // partial example only: only code and client_id are included String query = String.format("code=%s&client_id=%s", code, client_id); OutputStream out = con.getOutputStream(); out.write(query.getBytes("UTF-8")); 

In the Google OAuth2 documentation, an example HTTP POST request might look something like this:

 POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-Type: application/x-www-form-urlencoded code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu& client_id=8819981768.apps.googleusercontent.com& client_secret={client_secret}& redirect_uri=https://oauth2-login-demo.appspot.com/code& grant_type=authorization_code 
+3
source

Source: https://habr.com/ru/post/983194/


All Articles