ios - MSAL - 尝试对 Microsoft Graph 登录进行身份验证时无法将项目设置为钥匙串
问题描述
我正在尝试在我的 iOS 应用程序中与 Microsoft Graph 集成。我正在 XCode 上使用 Swift 开发。我遵循了本教程:
当我单击连接时,输入我的登录详细信息,它不断给我下面的错误消息。我已经尝试调试,它进入acquireTokenInteractively() 并打印错误。
我已经在 Microsoft 应用程序门户上注册了我的应用程序,在应用程序的功能选项卡上启用了钥匙串共享等,不确定为什么这不起作用..
感谢您的帮助。
import UIKit
import MSAL
class ViewController: UIViewController, UITextFieldDelegate, URLSessionDelegate {
// Update the below to your client ID you received in the portal. The below is for running the demo only
let kClientID = "a88969f1-61c7-4322-a9a0-9212bb96b782"
// These settings you don't need to edit unless you wish to attempt deeper scenarios with the app.
let kGraphURI = "https://graph.microsoft.com/v1.0/me/"
//let kScopes: [String] = ["https://graph.microsoft.com/user.read"]
let kAuthority = "https://login.microsoftonline.com/common"
var accessToken = String()
var applicationContext : MSALPublicClientApplication?
@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var signoutButton: UIButton!
@IBOutlet weak var loggingText: UITextView!
@IBAction func connectButtonTapped(_ sender: UIButton) {
print("Connect button tapped")
if self.currentAccount() == nil {
// We check to see if we have a current logged in account.
// If we don't, then we need to sign someone in.
self.acquireTokenInteractively()
} else {
self.acquireTokenSilently()
}
}
@IBAction func signoutButtonTapped(_ sender: UIButton) {
print("Signout button tapped")
guard let applicationContext = self.applicationContext else { return }
guard let account = self.currentAccount() else { return }
do {
/**
Removes all tokens from the cache for this application for the provided account
- account: The account to remove from the cache
*/
try applicationContext.remove(account)
self.loggingText.text = ""
self.signoutButton.isEnabled = false
} catch let error as NSError {
self.loggingText.text = "Received error signing account out: \(error)"
}
}
/**
Setup public client application in viewDidLoad
*/
override func viewDidLoad() {
super.viewDidLoad()
do {
/**
Initialize a MSALPublicClientApplication with a given clientID and authority
- clientId: The clientID of your application, you should get this from the app portal.
- authority: A URL indicating a directory that MSAL can use to obtain tokens. In Azure AD
it is of the form https://<instance/<tenant>, where <instance> is the
directory host (e.g. https://login.microsoftonline.com) and <tenant> is a
identifier within the directory itself (e.g. a domain associated to the
tenant, such as contoso.onmicrosoft.com, or the GUID representing the
TenantID property of the directory)
- error The error that occurred creating the application object, if any, if you're
not interested in the specific error pass in nil.
*/
guard let authorityURL = URL(string: kAuthority) else {
self.loggingText.text = "Unable to create authority URL"
return
}
let authority = try MSALAuthority(url: authorityURL)
self.applicationContext = try MSALPublicClientApplication(clientId: kClientID, authority: authority)
} catch let error {
self.loggingText.text = "Unable to create Application Context \(error)"
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
signoutButton.isEnabled = !self.accessToken.isEmpty
}
/**
This button will invoke the authorization flow.
*/
@IBAction func callGraphButton(_ sender: UIButton) {
if self.currentAccount() == nil {
// We check to see if we have a current logged in account.
// If we don't, then we need to sign someone in.
self.acquireTokenInteractively()
} else {
self.acquireTokenSilently()
}
}
func getContentWithToken() {
// Specify the Graph API endpoint
let url = URL(string: kGraphURI)
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.loggingText.text = "Couldn't get graph result: \(error)"
return
}
guard let result = try? JSONSerialization.jsonObject(with: data!, options: []) else {
self.loggingText.text = "Couldn't deserialize result JSON"
return
}
self.loggingText.text = "Result from Graph: \(result))"
}.resume()
}
func acquireTokenInteractively() {
guard let applicationContext = self.applicationContext else { return }
applicationContext.acquireToken(forScopes: ApplicationConstants.kScopes) { (result, error) in
if let error = error {
self.loggingText.text = "Could not acquire token: \(error)"
return
}
guard let result = result else {
self.loggingText.text = "Could not acquire token: No result returned"
return
}
self.accessToken = result.accessToken
self.loggingText.text = "Access token is \(self.accessToken)"
self.signoutButton.isEnabled = true
self.getContentWithToken()
}
}
func acquireTokenSilently() {
guard let applicationContext = self.applicationContext else { return }
/**
Acquire a token for an existing account silently
- forScopes: Permissions you want included in the access token received
in the result in the completionBlock. Not all scopes are
guaranteed to be included in the access token returned.
- account: An account object that we retrieved from the application object before that the
authentication flow will be locked down to.
- completionBlock: The completion block that will be called when the authentication
flow completes, or encounters an error.
*/
applicationContext.acquireTokenSilent(forScopes: ApplicationConstants.kScopes, account: self.currentAccount()!) { (result, error) in
if let error = error {
let nsError = error as NSError
// interactionRequired means we need to ask the user to sign-in. This usually happens
// when the user's Refresh Token is expired or if the user has changed their password
// among other possible reasons.
if (nsError.domain == MSALErrorDomain
&& nsError.code == MSALErrorCode.interactionRequired.rawValue) {
DispatchQueue.main.async {
self.acquireTokenInteractively()
}
} else {
self.loggingText.text = "Could not acquire token silently: \(error)"
}
return
}
guard let result = result else {
self.loggingText.text = "Could not acquire token: No result returned"
return
}
self.accessToken = result.accessToken
self.loggingText.text = "Refreshed Access token is \(self.accessToken)"
self.signoutButton.isEnabled = true
self.getContentWithToken()
}
}
func currentAccount() -> MSALAccount? {
guard let applicationContext = self.applicationContext else { return nil }
// We retrieve our current account by getting the first account from cache
// In multi-account applications, account should be retrieved by home account identifier or username instead
do {
let cachedAccounts = try applicationContext.allAccounts()
if !cachedAccounts.isEmpty {
return cachedAccounts.first
}
} catch let error as NSError {
self.loggingText.text = "Didn't find any accounts in cache: \(error)"
}
return nil
}
}
//
struct ApplicationConstants {
static let ResourceId = "https://graph.microsoft.com"
static let kAuthority = "https://login.microsoftonline.com/common/oauth2/v2.0"
static let kGraphURI = "https://graph.microsoft.com/v1.0/me/"
static let kScopes = ["https://graph.microsoft.com/Mail.ReadWrite",
"https://graph.microsoft.com/Mail.Send",
"https://graph.microsoft.com/Files.ReadWrite",
"https://graph.microsoft.com/User.ReadBasic.All"]
static var kClientID = "6d5a8e6d-0281-4003-8feb-43a9ca39d4d2"
enum MSGraphError: Error {
case nsErrorType(error: NSError)
}
}
解决方案
您需要确保已将正确的标识符添加到您的钥匙串共享组。默认值为com.microsoft.adalcache
。
推荐阅读
- ios - 从 Firebase 检索信息时,控制流如何工作?
- vba - 从共享驱动器加载的 Word 文档的本地副本无法使用 VBA 另存为 PDF 方法。不保存文档
- angular - Angular Input 设置焦点问题在 iOS 设备中不起作用
- ros - 如何将预序列化数据发布到 ROS?
- reactjs - 方法“text”意味着在 1 个节点上运行。找到了 0 个
- python - 在 docker Alpine 中安装 pandas
- ruby-on-rails - Google Cloud Talent 解决方案异常:Google::Cloud::PermissionDeniedError
- python - 非英语术语-文档矩阵
- c# - 使用 C# 验证 PS256 编码的 JWT
- vuejs2 - 触发 nuxt-link 初学者时出现网络错误