0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Salesfore Apexから外部システムのOAuthトークンを取得する

Posted at

はじめに

Apexから外部システムのOAuthトークンを取得する処理を実装しました。
(指定ログインを用いたコールアウトで、トークン取得は成功しても、認証ではじかれるケースがあったため)
認可方式は、Client Credentialsを想定しています。

Apexの実装

String END_POINT_AUTH = '外部システムの認証用エンドポイント';
String CLIENT_ID = '外部システムのclientId';
String CLIENT_SECRET = '外部システムのclientSecret';

HttpRequest req = new HttpRequest();
// リクエストヘッダ
req.setEndpoint(END_POINT_AUTH);
req.setMethod('POST');
String authString = CLIENT_ID + ':' + CLIENT_SECRET; 
String base64EncodedAuth = 
EncodingUtil.base64Encode(Blob.valueOf(authString));
req.setHeader('Authorization', 'Basic ' + base64EncodedAuth);

// リクエストボディ
String body = 'grant_type=client_credentials';
req.setBody(body);

Http http = new Http();
HttpResponse res = http.send(req);

// レスポンスボディをJSONとして解析
Map<String, Object> responseBody = (Map<String, Object>) JSON.deserializeUntyped(
  res.getBody()
);

// アクセストークンを取得
String accessToken = (String) responseBody.get('access_token');

補足

レスポンスボディの解釈は外部システムのレスポンスボディに合わせて変更する必要があります。
コールアウトするときには、リモートサイトの設定に外部システムのURLを設定しておく必要があります

参考文献

この記事は以下の情報を参考にして執筆しました。

OAuth Grant Types 概要

HTTP のクラス

サーバー間インテグレーション用の OAuth 2.0 クライアントログイン情報フロー

リモートサイトの設定の追加

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?