Search code examples
iosswiftparse-platformparse-server

How to authenticate a user in Parse iOS SDK using OAuth?


Parse Server offers OAuth authentication. How can I use the Parse Server's predefined OAuth modules, e.g. Facebook, to sign up a new user or login an existing user of the '_User' class?

The Parse Server docs give examples on how to configure the OAuth modules. But how do I use it in an iOS project to login or signup a user?


Solution

  • 1, create a class extends from both NSObject and PFUserAuthenticationDelegate.

    class AuthDelegate:NSObject, PFUserAuthenticationDelegate {
        func restoreAuthenticationWithAuthData(authData: [String : String]?) -> Bool {
            return true
        }
    }
    

    2, register this authentication delegate

    // parmeter 'forAuthType' is the name of file defined in 
    // https://github.com/parse-community/parse-server/blob/master/src/Adapters/Auth/index.js
    // such as: google, github, linkedin ......
    PFUser.registerAuthenticationDelegate(AuthDelegate(), forAuthType: "google")
    

    3, using PFUser.logInWithAuthTypeInBackground method to store user info to _User

    // for google oauth, authData format will be
    // ["id":"PUT_USER_ID_HERE","accesstoken":"PUT_TOKEN_HERE"]
    PFUser.logInWithAuthType(inBackground: "google", authData:[.....])
    

    4, you will see a record is created in _User, with only objectId and authData