这是本教程系列中的第四个教程,介绍如何使用 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 Graph API,了解有关 Microsoft Graph API 的详细信息。
测试你的应用
构建应用并将其部署到测试设备或模拟器。 现在应该能够登录并获取 Microsoft Entra ID 帐户的令牌。
用户首次登录你的应用时,Microsoft 身份验证服务将提示他们同意所请求的权限。 虽然大多数用户都能够同意,但某些 Microsoft Entra 租户已禁用用户同意功能,这要求管理员代表所有用户同意。 要支持此场景,请注册应用的范围。
你登录后,此应用将显示从 Microsoft Graph /me
终结点返回的数据。
后续步骤
在我们的多部分场景系列中,详细了解如何构建可调用受保护 Web API 的移动应用。