如何通过Client_ID、Client_Secret等参数获取Access Token?代码报错求助
Fixing "Invalid grant_type parameter or parameter missing" in Imgur OAuth2 Token Request
Let's break down what's going wrong with your code and fix it step by step:
Key Issues in Your Current Code
- Incorrect Grant Type & Parameter Names
- You used
authorization_Code(capital C) forgrant_type—the correct spelling isauthorization_code(lowercase c). But more importantly, since you're passingusernameandpassword, you should be using the Password Grant Type, which requiresgrant_type=passwordinstead ofauthorization_code(that's for the Authorization Code flow, which needs a pre-obtained code). - Your parameter names are wrong: OAuth2 expects
client_idandclient_secret(snake_case, no spaces), not"Client ID"and"Client Secret".
- You used
- Wrong API Endpoint
- You're sending the POST request to
Auth_URL(the authorization page URL), but the correct endpoint for fetching an access token isAccess_Token_URL. TheAuth_URLis for redirecting users to grant permission and get an authorization code, not directly retrieving tokens.
- You're sending the POST request to
- Redundant Authentication
- You're both passing client credentials as form parameters and using preemptive Basic Auth—you only need one of these methods for authentication.
Corrected Code (Password Grant Type)
Here's the fixed version that should work for the Password flow:
public class Authentication_Token { private String clientId = "9d99755c****d"; private String clientSecret = "dbdb21c0de1b***ab1d4cf6a4b92535ed2"; private String accessTokenUrl = "https://api.imgur.com/oauth2/token"; @Test public void oauth2PasswordGrant() { Response resp = given() .contentType("application/x-www-form-urlencoded") // Correct parameters for Password Grant Type .formParam("grant_type", "password") .formParam("client_id", clientId) .formParam("client_secret", clientSecret) .formParam("username", "testbot@gmail.com") .formParam("password", "testbota#1") .post(accessTokenUrl); // Print response to debug easily System.out.println(resp.getBody().asString()); } }
Note on Authorization Code Flow (Recommended for Production)
If you intended to use the more secure Authorization Code Grant Type (better for production apps that don't own the user's credentials), you'll need two steps:
- Redirect the user to
https://api.imgur.com/oauth2/authorizewith parameters likeclient_id,response_type=code,redirect_urito get an authorization code. - Exchange that code for an access token by sending a POST to
accessTokenUrlwithgrant_type=authorization_code,code=YOUR_AUTH_CODE,client_id,client_secret, andredirect_uri.
内容的提问来源于stack exchange,提问作者umeshinator
相关产品推荐
相关产品推荐

