この文章は Salesforce 機械翻訳システムを使用して翻訳されました。詳細はこちらをご参照ください。
英語に切り替える

OAuth 2.0 での認証の設定

OAuth 2.0 の設定では、ユーザインターフェース内とその他の場所でいくつかの設定を行う必要があります。手順に不明な点がある場合は、『REST API 開発者ガイド』または OAuth 2.0 のドキュメントを参照してください。

この章のサンプル Java コードでは Apache HttpClient ライブラリを使用します。このライブラリは http://hc.apache.org/httpcomponents-client-ga/ からダウンロードできます。

  1. Salesforce Classic では、[設定] から、[クイック検索] ボックスに「アプリケーション」と入力し、[アプリケーション] を選択します。Lightning Experience では、[クイック検索] ボックスに「アプリケーション」と入力し、[アプリケーションマネージャ] を選択します。[接続アプリケーション] 関連リストの [新規] をクリックして、新しい接続アプリケーションを作成します。

    ここで指定する [コールバック URL] は、Web アプリケーションのコールバック URL と同じです。Java を使用する場合、通常はこれはサーブレットです。また、セキュアである必要があります。http:// は機能せず、https:// のみが機能します。開発環境では、コールバック URL は https://my-website/_callback のような形になります。[保存] をクリックすると、[コンシューマ鍵] が作成され、表示されます。また、[コンシューマの秘密] が作成されます (表示するにはリンクをクリックします)。

    OAuth 2.0 仕様では、「コンシューマ」ではなく「クライアント」を使用します。Salesforce は OAuth 2.0 をサポートします。

    メモ

    Salesforce のリモートアクセスアプリケーションで使用される用語と、この手順の残りの部分にあるサンプルコードに含まれる値は次のように対応します。

    • client_id[コンシューマ鍵] に対応
    • client_secret[コンシューマの秘密] に対応
    • redirect_uri[コールバック URL] に対応

    その他に指定する必要のあるパラメータは grant_type です。OAuth 2.0 コールバックでは、サンプルに示すように、値は authorization_code です。これらのパラメータについての詳細は、「Salesforce での OAuth 2.0 の詳細」を参照してください。

    client_id (または consumer key) の値と client_secret (または consumer secret) が有効な場合、Salesforce はコールバックを、access_token. の値が含まれる redirect_uri に指定された URI に送信します。

  2. Java またはその他のクライアントアプリケーションから、認証 URL への要求を行い、grant_typeclient_idclient_secretusername、および password を渡します。次に例を示します。
    1HttpClient httpclient = new DefaultHttpClient();
    2HttpPost post = new HttpPost(baseURL);
    3
    4List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
    5
    6parametersBody.add(new BasicNameValuePair("grant_type", password));
    7parametersBody.add(new BasicNameValuePair("client_id", clientId));
    8parametersBody.add(new BasicNameValuePair("client_secret", client_secret));
    9parametersBody.add(new BasicNameValuePair("username", "auser@example.com"));
    10parametersBody.add(new BasicNameValuePair("password", "swordfish"));

    この認証方法は開発環境でのみ使用し、本番コードには使用しないでください。

    重要

この例では、セッション ID を取得 (認証) し、最初の応答に含まれるリソース https://instance.salesforce.com/id/00Dxxxxxxxxxxxx/005xxxxxxxxxxxx に従って、ユーザに関する詳細情報を取得します。

1public static void oAuthSessionProvider(String loginHost, String username,
2        String password, String clientId, String secret)
3        throws HttpException, IOException 
4{
5    // Set up an HTTP client that makes a connection to REST API.
6    DefaultHttpClient client = new DefaultHttpClient();
7    HttpParams params = client.getParams();
8    HttpClientParams.setCookiePolicy(params, CookiePolicy.RFC_2109);
9    params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);
10
11    // Set the SID.
12    System.out.println("Logging in as " + username + " in environment " + loginHost);
13    String baseUrl = loginHost + "/services/oauth2/token";
14    // Send a post request to the OAuth URL.
15    HttpPost oauthPost = new HttpPost(baseUrl);
16    // The request body must contain these 5 values.
17    List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
18    parametersBody.add(new BasicNameValuePair("grant_type", "password"));
19    parametersBody.add(new BasicNameValuePair("username", username));
20    parametersBody.add(new BasicNameValuePair("password", password));
21    parametersBody.add(new BasicNameValuePair("client_id", clientId));
22    parametersBody.add(new BasicNameValuePair("client_secret", secret));
23    oauthPost.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
24
25    // Execute the request.
26    System.out.println("POST " + baseUrl + "...\n");
27    HttpResponse response = client.execute(oauthPost);
28    int code = response.getStatusLine().getStatusCode();
29    Map<String, String> oauthLoginResponse = (Map<String, String>)
30        JSON.parse(EntityUtils.toString(response.getEntity()));
31    System.out.println("OAuth login response");
32    for (Map.Entry<String, String> entry : oauthLoginResponse.entrySet()) 
33    {
34        System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
35    }
36    System.out.println("");
37
38    // Get user info.
39    String userIdEndpoint = oauthLoginResponse.get("id");
40    String accessToken = oauthLoginResponse.get("access_token");
41    List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
42    qsList.add(new BasicNameValuePair("oauth_token", accessToken));
43    String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
44    HttpGet userInfoRequest = new HttpGet(userIdEndpoint + "?" + queryString);
45    HttpResponse userInfoResponse = client.execute(userInfoRequest);
46    Map<String, Object> userInfo = (Map<String, Object>)
47        JSON.parse(EntityUtils.toString(userInfoResponse.getEntity()));
48    System.out.println("User info response");
49    for (Map.Entry<String, Object> entry : userInfo.entrySet()) 
50    {
51        System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
52    }
53    System.out.println("");
54
55    // Use the user info in interesting ways.
56    System.out.println("Username is " + userInfo.get("username"));
57    System.out.println("User's email is " + userInfo.get("email"));
58    Map<String, String> urls = (Map<String, String>)userInfo.get("urls");
59    System.out.println("REST API url is " + urls.get("rest").replace("{version}", "46.0"));
60}
このコードからの出力は、次のようになります。
1Logging in as auser@example.com in environment https://login.salesforce.com
2POST https://login.salesforce.com/services/oauth2/token...
3
4OAuth login response
5  id = https://login.salesforce.com/id/00D30000000ehjIEAQ/00530000003THy8AAG
6  issued_at = 1334961666037
7  instance_url = https://instance.salesforce.com
8  access_token = 00D30000000ehjI!ARYAQHc.0Mlmz.DCg3HRNF.SmsSn5njPkry2SM6pb6rjCOqfAODaUkv5CGksRSPRb.xb
9  signature = 8M9VWBoaEk+Bs//yD+BfrUR/+5tkNLgXAIwal1PMwsY=
10
11User info response
12  user_type = STANDARD
13  status = {created_date=2012-04-08T16:44:58.000+0000, body=Hello}
14  urls = {sobjects=https://instance.salesforce.com/services/data/v{version}/sobjects/, feeds=https://instance.salesforce.com/services/data/v{version}/chatter/feeds, users=https://instance.salesforce.com/services/data/v{version}/chatter/users, query=https://instance.salesforce.com/services/data/v{version}/query/, enterprise=https://instance.salesforce.com/services/Soap/c/{version}/00D30000000ehjI, recent=https://instance.salesforce.com/services/data/v{version}/recent/, feed_items=https://instance.salesforce.com/services/data/v{version}/chatter/feed-items, search=https://instance.salesforce.com/services/data/v{version}/search/, partner=https://instance.salesforce.com/services/Soap/u/{version}/00D30000000ehjI, rest=https://instance.salesforce.com/services/data/v{version}/, groups=https://instance.salesforce.com/services/data/v{version}/chatter/groups, metadata=https://instance.salesforce.com/services/Soap/m/{version}/00D30000000ehjI, profile=https://instance.salesforce.com/00530000003THy8AAG}
15  locale = en_US
16  asserted_user = true
17  id = https://login.salesforce.com/id/00D30000000ehjIEAQ/00530000003THy8AAG
18  nick_name = SampleNickname
19  photos = {picture=https://instance.content.force.com/profilephoto/005/F, thumbnail=https://c.instance.content.force.com/profilephoto/005/T}
20  display_name = Sample User
21  first_name = Admin
22  last_modified_date = 2012-04-19T04:35:29.000+0000
23  username = auser@example.com
24  email = emailaddr@example.com
25  organization_id = 00D30000000ehjIEAQ
26  last_name = User
27  utcOffset = -28800000
28  active = true
29  user_id = 00530000003THy8AAG
30  language = en_US
31
32Username is auser@example.com
33User's email is emailaddr@example.com
34REST API url is https://instance.salesforce.com/services/data/v46.0/