この記事では、「Microsoft Graph を使用して Java アプリをビルドする」で作成したアプリケーションにユーザー認証を追加します。 次に、Microsoft Graph ユーザー API を使用して、認証されたユーザーを取得します。
ユーザー認証を追加する
Java 用の Azure Identity クライアント ライブラリには、OAuth2 トークン フローを実装する多くのTokenCredential クラスが用意されています。
Microsoft Graph SDK for Java では、これらのクラスを使用して Microsoft Graph への呼び出しを認証します。
ユーザー認証用に Graph クライアントを構成する
まず、 DeviceCodeCredential クラスを使用して 、デバイス コード フローを使用してアクセス トークンを要求します。
./app/src/メイン/java/graphtutorial ディレクトリに Graph.java という名前の新しいファイルを作成し、そのファイルに次のコードを追加します。
package graphtutorial; import java.util.List; import java.util.Properties; import java.util.function.Consumer; import com.azure.core.credential.AccessToken; import com.azure.core.credential.TokenRequestContext; import com.azure.identity.DeviceCodeCredential; import com.azure.identity.DeviceCodeCredentialBuilder; import com.azure.identity.DeviceCodeInfo; import com.microsoft.graph.models.BodyType; import com.microsoft.graph.models.EmailAddress; import com.microsoft.graph.models.ItemBody; import com.microsoft.graph.models.Message; import com.microsoft.graph.models.MessageCollectionResponse; import com.microsoft.graph.models.Recipient; import com.microsoft.graph.models.User; import com.microsoft.graph.serviceclient.GraphServiceClient; import com.microsoft.graph.users.item.sendmail.SendMailPostRequestBody;空の Graph クラス定義を追加します。
public class Graph { }Graphクラスに以下のコードを追加します。private static Properties _properties; private static DeviceCodeCredential _deviceCodeCredential; private static GraphServiceClient _userClient; public static void initializeGraphForUserAuth(Properties properties, Consumer<DeviceCodeInfo> challenge) throws Exception { // Ensure properties isn't null if (properties == null) { throw new Exception("Properties cannot be null"); } _properties = properties; final String clientId = properties.getProperty("app.clientId"); final String tenantId = properties.getProperty("app.tenantId"); final String[] graphUserScopes = properties.getProperty("app.graphUserScopes").split(","); _deviceCodeCredential = new DeviceCodeCredentialBuilder() .clientId(clientId) .tenantId(tenantId) .challengeConsumer(challenge) .build(); _userClient = new GraphServiceClient(_deviceCodeCredential, graphUserScopes); }App.javaの空の
initializeGraph関数 を 次のように置き換えます。private static void initializeGraph(Properties properties) { try { Graph.initializeGraphForUserAuth(properties, challenge -> System.out.println(challenge.getMessage())); } catch (Exception e) { System.out.println("Error initializing Graph for user auth"); System.out.println(e.getMessage()); } }
このコードでは、 DeviceCodeCredential オブジェクトと GraphServiceClient オブジェクトの 2 つのプライベート プロパティを宣言します。
InitializeGraphForUserAuth関数は、DeviceCodeCredentialの新しいインスタンスを作成し、そのインスタンスを使用してGraphServiceClientの新しいインスタンスを作成します。 API 呼び出しが _userClientを介して Microsoft Graph に対して行われるたびに、提供された資格情報を使用してアクセス トークンを取得します。
DeviceCodeCredential をテストする
次に、 DeviceCodeCredentialからアクセス トークンを取得するコードを追加します。
次の関数を
Graphクラスに追加します。public static String getUserToken() throws Exception { // Ensure credential isn't null if (_deviceCodeCredential == null) { throw new Exception("Graph has not been initialized for user auth"); } final String[] graphUserScopes = _properties.getProperty("app.graphUserScopes").split(","); final TokenRequestContext context = new TokenRequestContext(); context.addScopes(graphUserScopes); final AccessToken token = _deviceCodeCredential.getTokenSync(context); return token.getToken(); }App.javaの空の
displayAccessToken関数 を 次のように置き換えます。private static void displayAccessToken() { try { final String accessToken = Graph.getUserToken(); System.out.println("Access token: " + accessToken); } catch (Exception e) { System.out.println("Error getting access token"); System.out.println(e.getMessage()); } }アプリをビルドして実行します。 オプションの入力を求められたら、「
1」と入力します。 アプリケーションに URL とデバイス コードが表示されます。Java Graph Tutorial Please choose one of the following options: 0. Exit 1. Display access token 2. List my inbox 3. Send mail 4. Make a Graph call 1 To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code RB2RUD56D to authenticate.ブラウザーを開き、表示された URL を参照します。 指定したコードを入力し、サインインします。
重要
https://microsoft.com/deviceloginを参照するときにブラウザーにログインしている既存の Microsoft 365 アカウントに注意してください。 プロファイル、ゲスト モード、プライベート モードなどのブラウザー機能を使用して、テストに使用するアカウントとして認証することを確認します。完了したら、アプリケーションに戻り、アクセス トークンを表示します。
ヒント
検証とデバッグ のみを目的として、 https://jwt.msで Microsoft のオンライン トークン パーサーを使用してユーザー アクセス トークンをデコードできます (職場または学校アカウントの場合のみ)。 トークンの解析は、Microsoft Graph を呼び出すときにトークン エラーが発生した場合に役立ちます。 たとえば、トークン内の
scp要求に、想定される Microsoft Graph アクセス許可スコープが含まれていることを確認します。
ユーザーを取得する
認証が構成されたので、最初の Microsoft Graph API呼び出しを行うことができます。 認証されたユーザーの名前と電子メール アドレスを取得するコードを追加します。
Graph.javaを開き、次の関数を
Graphクラスに追加します。public static User getUser() throws Exception { // Ensure client isn't null if (_userClient == null) { throw new Exception("Graph has not been initialized for user auth"); } return _userClient.me().get(requestConfig -> { requestConfig.queryParameters.select = new String[] {"displayName", "mail", "userPrincipalName"}; }); }App.javaの空の
greetUser関数 を 次のように置き換えます。private static void greetUser() { try { final User user = Graph.getUser(); // For Work/school accounts, email is in mail property // Personal accounts, email is in userPrincipalName final String email = user.getMail() == null ? user.getUserPrincipalName() : user.getMail(); System.out.println("Hello, " + user.getDisplayName() + "!"); System.out.println("Email: " + email); } catch (Exception e) { System.out.println("Error getting user"); System.out.println(e.getMessage()); } }
アプリを今すぐ実行すると、サインインした後に名前で歓迎されます。
Hello, Megan Bowen!
Email: MeganB@contoso.com
コードの説明
greetUser関数のコードについて考えてみましょう。 ほんの数行ですが、注意する必要がある重要な詳細がいくつかあります。
'me' へのアクセス
関数は、Get user API への要求をビルドする_userClient.me要求ビルダーを使用します。 この API には、次の 2 つの方法でアクセスできます。
GET /me
GET /users/{user-id}
この場合、コードは GET /me API エンドポイントを呼び出します。 このエンドポイントは、ユーザー ID を知らずに認証されたユーザーを取得するためのショートカット メソッドです。
注:
GET /me API エンドポイントは認証されたユーザーを取得するため、ユーザー認証を使用するアプリでのみ使用できます。 アプリ専用認証アプリは、このエンドポイントにアクセスできません。
特定のプロパティの要求
関数は、要求構成で select プロパティを使用して、必要なプロパティのセットを指定します。 このプロパティは、 $select クエリ パラメーター を API 呼び出しに追加します。
厳密に型指定された戻り値の型
関数は、API からの JSON 応答から逆シリアル化された com.microsoft.graph.models.User オブジェクトを返します。 コードでは selectが使用されるため、返される User オブジェクトには、要求されたプロパティのみが値を持ちます。 その他のすべてのプロパティには既定値があります。