适用于: 员工租户
外部租户(了解详细信息)
这是本教程系列中的第三个教程,介绍如何使用 Microsoft Entra 外部 ID 调用受保护的 Web API。
在本教程中,你将:
- 调用受保护的 Web API
先决条件
调用受保护的 Web API
在“appsrc>mainjava>com.example(你的应用名称)”中。>> 创建以下 Android 片段:
- MSGraphRequestWrapper 的
打开 MSGraphRequestWrapper.java ,并将代码替换为以下代码片段,以使用 MSAL 提供的令牌调用Microsoft图形 API:
package com.azuresamples.msalandroidapp; import android.content.Context; import android.util.Log; import androidx.annotation.NonNull; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class MSGraphRequestWrapper { private static final String TAG = MSGraphRequestWrapper.class.getSimpleName(); // See: https://docs.microsoft.com/en-us/graph/deployments#microsoft-graph-and-graph-explorer-service-root-endpoints public static final String MS_GRAPH_ROOT_ENDPOINT = "https://graph.microsoft.com/"; /** * Use Volley to make an HTTP request with * 1) a given MSGraph resource URL * 2) an access token * to obtain MSGraph data. **/ public static void callGraphAPIUsingVolley(@NonNull final Context context, @NonNull final String graphResourceUrl, @NonNull final String accessToken, @NonNull final Response.Listener<JSONObject> responseListener, @NonNull final Response.ErrorListener errorListener) { Log.d(TAG, "Starting volley request to graph"); /* Make sure we have a token to send to graph */ if (accessToken == null || accessToken.length() == 0) { return; } RequestQueue queue = Volley.newRequestQueue(context); JSONObject parameters = new JSONObject(); try { parameters.put("key", "value"); } catch (Exception e) { Log.d(TAG, "Failed to put parameters: " + e.toString()); } JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, graphResourceUrl, parameters, responseListener, errorListener) { @Override public Map<String, String> getHeaders() { Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + accessToken); return headers; } }; Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString()); request.setRetryPolicy(new DefaultRetryPolicy( 3000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); queue.add(request); } }
测试你的应用
构建应用并将其部署到测试设备或模拟器。 你应该能够登录并获取 Microsoft Entra ID 的令牌。