0auth2与Microsoft重定向问题

时间:2018-05-09 21:05:16

标签: ios swift oauth-2.0 outlook

我得到了提供身份验证的应用程序。它会通过“接受”或“拒绝”按钮打开并请求用户权限。但是,当我点击接受。它无法重新指挥。

我按照微软发布的有关设置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” 我已使用KTracker2的原生重定向注册了应用程序@ https://apps.dev.microsoft.com/?lc=1033#/application/584bb6db-5b71-4d7c-9015-fab8a9dfae4c:// oauth2 / callback

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

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您需要处理AppDelegate中的回调

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