適用於:
員工租戶
外部租用戶 (深入瞭解)
這是教學課程系列中的第四個教學課程,會引導您使用 Microsoft Entra ID 登入使用者和呼叫受保護的 Web API。
在本教學課程中,您會:
- 呼叫受保護的 Web API。
先決條件
呼叫 API
一旦您有令牌,您的應用程式就可以在 HTTP 標頭中使用它,對 Microsoft Graph 提出授權要求:
| 標頭鍵 | 價值 |
|---|---|
| 授權 | 承載者 <存取令牌> |
將下列程式代碼新增至 ViewController 類別:
func getContentWithToken() {
// Specify the Graph API endpoint
let graphURI = getGraphEndpoint()
let url = URL(string: graphURI)
var request = URLRequest(url: url!)
// Set the Authorization header for the request. We use Bearer tokens, so we specify Bearer + the token we got from the result
request.setValue("Bearer \(self.accessToken)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
self.updateLogging(text: "Couldn't get graph result: \(error)")
return
}
guard let result = try? JSONSerialization.jsonObject(with: data!, options: []) else {
self.updateLogging(text: "Couldn't deserialize result JSON")
return
}
self.updateLogging(text: "Result from Graph: \(result))")
}.resume()
}
若要深入瞭解Microsoft圖形 API,請參閱 Microsoft圖形 API。
測試您的應用程式
建置應用程式並將其部署至測試裝置或模擬器。 您應該能夠登入並取得Microsoft Entra ID 或個人Microsoft帳戶的令牌。
使用者第一次登入您的應用程式時,系統會提示使用者Microsoft身分識別同意所要求的許可權。 雖然大部分的使用者都能夠同意,但有些Microsoft Entra 租使用者已停用使用者同意,這需要系統管理員代表所有使用者同意。 若要支援此案例,請註冊您的應用程式範圍。
登入之後,應用程式會顯示從 Microsoft Graph /me 端點傳回的數據。
後續步驟
瞭解更多關於建置能呼叫受保護網頁 API 的行動應用程式,這將在我們的多部情境系列中進行探討。
這是教學課程系列中的第四個教學課程,會引導您使用 Microsoft Entra External ID 來登入使用者和呼叫受保護的 Web API。
在本教學課程中,您會:
- 呼叫受保護的 Web API。
先決條件
公開至少一個範圍(委派許可權)和一個應用程式角色(應用程式許可權)的 API 註冊,例如 ToDoList.Read。 如果您尚未這麼做,請遵循範例 iOS 行動應用程式中關於呼叫 API 的指示,以便擁有一個功能完備且受保護的 ASP.NET Core Web API。 請確定您完成下列步驟:
- 註冊 Web API 應用程式。
- 設定 API 範圍。
- 設定應用程式角色。
- 設定選擇性權利要求。
- 複製或下載範例 Web API。
- 設定和執行範例 Web API。
呼叫 API
若要從 iOS 應用程式呼叫受保護的 Web API,請使用下列程式代碼:
func getContentWithToken() {
// Specify the API endpoint in _Configuration.swift_ file you created earlier
guard let url = URL(string: Configuration.kProtectedAPIEndpoint) else {
let errorMessage = "Invalid API url"
print(errorMessage)
updateLogging(text: errorMessage)
return
}
var request = URLRequest(url: url)
// Set the Authorization header for the request. We use Bearer tokens, so we specify Bearer + the token we got from the result
request.setValue("Bearer \(self.accessToken)", forHTTPHeaderField: "Authorization")
self.updateLogging(text: "Performing request...")
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
self.updateLogging(text: "Couldn't get API result: \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode)
else {
self.updateLogging(text: "Couldn't get API result: \(error)")
return
}
guard let data = data, let result = try? JSONSerialization.jsonObject(with: data, options: []) else {
self.updateLogging(text: "Couldn't deserialize result JSON")
return
}
self.updateLogging(text: """
Accessed API successfully using access token.
HTTP response code: \(httpResponse.statusCode)
HTTP response body: \(result)
""")
}.resume()
}
程序代碼會指定 API 端點,以確保其有效性。 然後,它會建構要求物件,並使用取得的存取令牌來設定授權標頭。 記錄要求起始之後,它會使用 URLSession以異步方式執行要求。
完成操作後,它會檢查要求期間是否有任何錯誤。 如果發生錯誤,它會記錄對應的訊息。 接下來,它會驗證 HTTP 回應的成功,確保其落在 200 到 299 狀態代碼的範圍內。 之後,它會反序列化接收到的 JSON 資料。 最後,它會更新記錄文字,指出成功存取 API 並包含相關的 HTTP 回應詳情。