Using SFAuthenticationSession to log in user to Microsoft Graph

僤鯓⒐⒋嵵緔 提交于 2019-12-11 23:18:55

问题


I've been using p2-oauth2 library earlier to be able to log in through a safariViewController, but since the latest iOS version (11.3) I found out that my app were crashing all the time when the user tries to log in. I didn't get any error messages, but after a while I found out that SFAuthenticationSessions is the way to go when using SSO (single sign on).

My old code were pretty much like this (Using p2_oauth2):

static var oauth2 = OAuth2CodeGrant(settings: [
    "client_id": "myClientID",
    "authorize_uri": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
    "token_uri": "https://login.microsoftonline.com/common/oauth2/v2.0/token",
    "scope": "User.Read Mail.Read Calendars.ReadWrite Calendars.Read Calendars.Read.Shared Offline_access",
    "redirect_uris": ["myRedirectURI"],
    "keychain": true
    ])

func loginToOffice365(completion: @escaping (_ error: Error? ) -> ()) {
    var userDataRequest: URLRequest {
        var request = URLRequest(url: URL(string: "https://graph.microsoft.com/v1.0/me/")!)
        request.setValue("Bearer \(OauthManager.oauth2.accessToken ?? "")", forHTTPHeaderField: "Authorization")
        return request
    }

    alamofireManager.request(userDataRequest).validate().responseJSON { 
 (response) in
    switch response.result {
    case .success( _):
    //Handle user information
        completion(nil)
    case .failure(let error):
        completion(error)
            }
        }
}

I tried to implement in SFAuthenticationSession in my project, and it was requiring a URL as a parameter. So I have been searching for a while for a Microsoft URL to make it possible to send in clientId, scope, and redirectURI in the same URL. And here's the result so far:

let url = URL(string: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?state=78E99F6B&response_type=code&scope=User.Read+Mail.Read+Calendars.ReadWrite+Calendars.Read+Calendars.Read.Shared&redirect_uri=MYREDIRECTURI&client_id=MYCLIENTID")!
        OauthManager.authenticationSession = SFAuthenticationSession(url: url, callbackURLScheme: nil, completionHandler: { (successUrl: URL?, error: Error?) in
            if let error = error {
                print(error)
                completion(error)
            } else {
                var accessToken = ""
                if let absolutString = successUrl?.absoluteString, let urlComponents = URLComponents(string: absolutString)?.query {
                    accessToken = urlComponents
                }
                print(accessToken)
                completion(nil)
            }
        })
        OauthManager.authenticationSession?.start()

So now I finally received an access token from Microsoft. But where should I go from here? How do I get refresh tokens, make it possible to start calling Microsoft graph API calls?

If you know any better solution or any advice I'll be glad to receive them! This is my first project using login, because I'm fairly new to Swift.

Update:

I can also mention that Microsoft documentation recommends using these libraries:

  • Microsoft Authentication Library (MSAL) client libraries are available for .NET, JavaScript, Android, and Objective-C. All platforms are in production-supported preview, and, in the event breaking changes are introduced, Microsoft guarantees a path to upgrade.
  • Server middleware from Microsoft is available for .NET Core and ASP.NET (OWIN OpenID Connect and OAuth) and for Node.js (Microsoft Azure AD Passport.js).
  • The v2.0 endpoint is compatible with many third-party authentication libraries.

https://developer.microsoft.com/en-us/graph/docs/concepts/auth_overview

I've tried MSAL and AppAuth, but they just didn't gave me any response back.


回答1:


@Paulw11 found the answer.

I was using a method, which worked fine up until XCode 9.3 and iOS 11.3:

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    return true
}

But I had to change to the following method to make it work:

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



回答2:


This is fixed in Xcode 9.4 and worked fine as we tested it. There is indeed a problem on Xcode 9.3



来源:https://stackoverflow.com/questions/49773318/using-sfauthenticationsession-to-log-in-user-to-microsoft-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!