ios - 0auth2 与 Microsoft 的重定向问题

标签 ios swift oauth-2.0 outlook

我得到了提供身份验证的应用程序。它打开并通过接受或拒绝按钮请求用户权限。但是,当我单击“接受”时。重定向失败。

我按照 Microsoft 发布的有关设置 iOS 应用程序的教程进行操作。

相关信息:

代码:

import Foundation
import p2_OAuth2
import SwiftyJSON

class OutlookService {

// Configure the OAuth2 framework for Azure
private static let oauth2Settings = [
    "client_id" : "584bb6db-5b71-4d7c-9015-fab8a9dfae4c",
    "authorize_uri": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
    "token_uri": "https://login.microsoftonline.com/common/oauth2/v2.0/token",
    "scope": "openid profile offline_access User.Read Mail.Read Calendars.Read",
    "redirect_uris": ["KTracker2://oauth2/callback"],
    "verbose": true,
    ] as OAuth2JSON

private static var sharedService: OutlookService = {
    let service = OutlookService()
    return service
}()

private let oauth2: OAuth2CodeGrant

private init() {
    oauth2 = OAuth2CodeGrant(settings: OutlookService.oauth2Settings)
    oauth2.authConfig.authorizeEmbedded = true
    oauth2.authConfig.ui.useSafariView = false

    userEmail = ""
}

class func shared() -> OutlookService {
    return sharedService
}

var isLoggedIn: Bool {
    get {
        return oauth2.hasUnexpiredAccessToken() || oauth2.refreshToken != nil
    }
}

func handleOAuthCallback(url: URL) -> Void {
    oauth2.handleRedirectURL(url)
}

func login(from: AnyObject, callback: @escaping (String?) -> Void) -> Void {
    oauth2.authorizeEmbedded(from: from) {
        result, error in
        if let unwrappedError = error {
            callback(unwrappedError.description)
        } else {
            if let unwrappedResult = result, let token = unwrappedResult["access_token"] as? String {
                // Print the access token to debug log
                NSLog("Access token: \(token)")
                callback(nil)
            }
        }
    }
}

func logout() -> Void {
    oauth2.forgetTokens()
}

func makeApiCall(api: String, params: [String: String]? = nil, callback: @escaping (JSON?) -> Void) -> Void {
    // Build the request URL
    var urlBuilder = URLComponents(string: "https://graph.microsoft.com")!
    urlBuilder.path = api

    if let unwrappedParams = params {
        // Add query parameters to URL
        urlBuilder.queryItems = [URLQueryItem]()
        for (paramName, paramValue) in unwrappedParams {
            urlBuilder.queryItems?.append(
                URLQueryItem(name: paramName, value: paramValue))
        }
    }

    let apiUrl = urlBuilder.url!
    NSLog("Making request to \(apiUrl)")

    var req = oauth2.request(forURL: apiUrl)
    req.addValue("application/json", forHTTPHeaderField: "Accept")

    let loader = OAuth2DataLoader(oauth2: oauth2)

    // Uncomment this line to get verbose request/response info in
    // Xcode output window
    //loader.logger = OAuth2DebugLogger(.trace)

    loader.perform(request: req) {
        response in
        do {
            let dict = try response.responseJSON()
            DispatchQueue.main.async {
                let result = JSON(dict)
                callback(result)
            }
        }
        catch let error {
            DispatchQueue.main.async {
                let result = JSON(error)
                callback(result)
            }
        }
    }
}

private var userEmail: String

func getUserEmail(callback: @escaping (String?) -> Void) -> Void {
    // If we don't have the user's email, get it from
    // the API
    if (userEmail.isEmpty) {
        makeApiCall(api: "/v1.0/me") {
            result in
            if let unwrappedResult = result {
                let email = unwrappedResult["mail"].stringValue
                self.userEmail = email
                callback(email)
            } else {
                callback(nil)
            }
        }
    } else {
        callback(userEmail)
    }
}

func getInboxMessages(callback: @escaping (JSON?) -> Void) -> Void {
    let apiParams = [
        "$select": "subject,receivedDateTime,from",
        "$orderby": "receivedDateTime DESC",
        "$top": "10"
    ]

    makeApiCall(api: "/v1.0/me/mailfolders/inbox/messages", params: apiParams) {
        result in
        callback(result)
    }
}

func getEvents(callback: @escaping (JSON?) -> Void) -> Void {
    let apiParams = [
        "$select": "subject,start,end",
        "$orderby": "start/dateTime ASC",
        "$top": "10"
    ]

    makeApiCall(api: "/v1.0/me/events", params: apiParams) {
        result in
        callback(result)
    }
}

func getContacts(callback: @escaping (JSON?) -> Void) -> Void {
    let apiParams = [
        "$select": "givenName,surname,emailAddresses",
        "$orderby": "givenName ASC",
        "$top": "10"
    ]

    makeApiCall(api: "/v1.0/me/contacts", params: apiParams) {
        result in
        callback(result)
    }
}

}

我添加了 urlscheme“KTracker2” 我已注册该应用程序@https://apps.dev.microsoft.com/?lc=1033#/application/584bb6db-5b71-4d7c-9015-fab8a9dfae4c使用 KTracker2://oauth2/callback 的 native 重定向

我想做的就是让身份验证页面重定向回我的本地 ios 应用程序。

感谢您的帮助

最佳答案

您需要处理AppDelegate内部的回调

func application(_ app: UIApplication, open url: URL,
                 options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
  OutlookService.sharedService.handleOAuthCallback(url: url)
  return true
}

关于ios - 0auth2 与 Microsoft 的重定向问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50262037/

相关文章:

xcode - 当返回类型可选时调用方法时显示消息

android - 具有 Web View 的 native 移动应用程序的 SSO 方法?

swift - 如何在无用户应用程序上使用 Google Api 上传到单个 Youtube channel

ios - 为什么 iPhone X 会忽略 UICollectionView 的 UIEdgeInsets?

ios - 如何在 iPhone 上保存数据?

ios - CocoaLumberjack 错误 : Symbol not found: _objc_storeStrong

oauth - DotNetOpenAuth 谷歌 OAuth2

iOS - 如果我在描述文本中发送 "&",Pinterest 分享描述文本不起作用

ios - 创建使用外部 Pod 的自定义 Pod

java - 我正在实例化从 Java (J2ObjC) 转译的 Swift 非 ARC Objective-C 类,它是否泄漏安全?