如何在salesforce.com中使用grant_type = password oauth流程?

Sym*_*ric 8 passwords oauth salesforce

我试图让使用用户名,密码流的授权令牌(在最后一节中描述文章).

我正在发送以下请求(使用Python的httplib,如果相关的话):

https://login.salesforce.com/services/oauth2/token

POST data:

username=<un>&client_secret=<consumer_secret>&password=<pw+token>&grant_type=password&client_id=<consumer_key>
Run Code Online (Sandbox Code Playgroud)

得到回应:

400 Bad Request
{"error":"unsupported_grant_type","error_description":"grant type not supported"}
Run Code Online (Sandbox Code Playgroud)

密码grant_type真的不受支持,或者我错过了什么?即使我发送肯定有效的grant_type(例如authorization_code),它似乎也会出现此错误.

请注意,我已经试过在回答的建议在这里,他们不为我工作.

sup*_*ell 21

通常这是因为内容类型标头尚未设置为正确的值,它应该是application/x-www-form-urlencoded.

还要确保您的参数已正确编码(特别是如果您手动构建POST有效负载).


Chi*_*hta 6

下面是关于如何在JAVA中使用grantforce = password oauth flow和salesforce.com的详细函数/逻辑:

    // Authenticate via OAuth
    JSONObject response = oauthLogin();
    System.out.println("Login response: " + response.toString(2));
    if (!response.has("access_token")) {
        throw new Exception("OAuth failed: " + response.toString());
    }

    ..........................


    private static JSONObject oauthLogin() throws Exception {

    org.eclipse.jetty.client.HttpClient jettyHttpClient = new org.eclipse.jetty.client.HttpClient();
    jettyHttpClient.start();

    String url = LOGIN_SERVER + "/services/oauth2/token";

    ContentExchange exchange = new ContentExchange();
    exchange.setMethod("POST");
    exchange.setURL(url);

    String message = "grant_type=password&client_id=" + CLIENT_ID
            + "&client_secret=" + CLIENT_SECRET + "&username=" + USERNAME
            + "&password=" + PASSWORD;

    exchange.setRequestHeader("Content-Type",
            "application/x-www-form-urlencoded");
    exchange.setRequestContentSource(new ByteArrayInputStream(message
            .getBytes("UTF-8")));

    jettyHttpClient.send(exchange);
    exchange.waitForDone();

    return new JSONObject(new JSONTokener(exchange.getResponseContent()));
}
Run Code Online (Sandbox Code Playgroud)