Google登录服务器验证代码无iOS?

时间:2017-02-24 09:20:44

标签: ios swift google-api google-oauth gmail-api

我们已在我们的应用程序中登录Google。我们在登录请求时提供serverClientID。

我们将user.serverAuthCode设为nil。

我们的要求如下:

func googleLogin(){
            var configureError: NSError?
            GGLContext.sharedInstance().configureWithError(&configureError)
            assert(configureError == nil, "Error configuring Google services: \(configureError)")

            let gid = GIDSignIn.sharedInstance()
            if let path = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist") {
                let myDict = NSDictionary(contentsOfFile: path)
                gid?.serverClientID = "our servers cliet id as configured over firebase"

// This client id of our ios app we are getting from
// GoogleService-info.plist 
                gid?.clientID = myDict!.value(forKey: "CLIENT_ID") as! String

            }
            //        gid?.serverClientID = "our_servers" // TODO: fetch from plist
            gid?.scopes.append("https://www.googleapis.com/auth/gmail.readonly")
            print("\nClient Id: \(gid!.clientID!) Server Client Id: \(gid!.serverClientID!)\n")
            gid?.delegate = self

        }

我们正试图获得serverAuthCode如下:

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if (error == nil) {
            // Perform any operations on signed in user here.
            let auth = user.serverAuthCode
            print(auth)
            let fullName = user.profile.name
         } else {
            print("\(error.localizedDescription)")
        }

    }

但它的serverAuthCode为空,我们不确定可能出现的问题。

6 个答案:

答案 0 :(得分:5)

GIDSignInDelegate ,GIDSignInUIDelegate使用2位代表。

let signin : GIDSignIn = GIDSignIn .sharedInstance()
signin.shouldFetchBasicProfile = true;
signin.uiDelegate = self
signin.delegate = self
GIDSignIn.sharedInstance().signInSilently() // this for swift 3.0
GIDSignIn.sharedInstance().signIn()

提供一个视图,提示用户使用Google登录

func sign(_ signIn: GIDSignIn!,
          present viewController: UIViewController!) {
    self.present(viewController, animated: true, completion: nil)
}

取消“使用Google登录”视图

func sign(_ signIn: GIDSignIn!,
          dismiss viewController: UIViewController!) {
    self.dismiss(animated: true, completion: nil)
}

已完成登录

    public func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {

        if (error == nil) {
            // Perform any operations on signed in user here.
            let userId = user.userID                  // For client-side use only!
            let idToken = user.authentication.idToken // Safe to send to the server
            let fullName = user.profile.name
            let givenName = user.profile.givenName
            let familyName = user.profile.familyName
            let email = user.profile.email
            let imageurl = user.profile.imageURL(withDimension: 1080)
            print("Gmail id %@" ,userId!)
            print("Gmail token %@" ,idToken!)
            print("Gmail full name %@" ,fullName!)
            print("Gmail first name %@" ,givenName!)
            print("Gmail last name %@" ,familyName!)
            print("Gmail emailid %@" ,email!)

            print("Gmail id %@" ,imageurl!)

        } else {
            print("\(error.localizedDescription)")
        }
    }

不要忘记将其添加到info.plist文件中

  <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>com.googleusercontent.apps.************************</string>
        </array>
    </dict>

答案 1 :(得分:5)

要注意的是,服务器身份验证代码仅在用户首次登录时才发送。用户必须刚刚看到确认屏幕。在所有后续登录中,将不发送服务器身份验证代码。转到https://security.google.com/settings/security/permissions并删除您的应用程序的凭据,然后您将获得服务器身份验证代码。

答案 2 :(得分:2)

Swift / IOS 使用谷歌登录

我可以用

解决同样的问题

googleUser.authentication.idToken

    func sign(_ signIn: GIDSignIn!, didSignInFor googleUser: GIDGoogleUser!, withError error: Error!) {
    if let error = error {
        if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue {
            print("The user has not signed in before or they have since signed out.")
        } else {
            print("\(error.localizedDescription)")
        }
        return
    }
    // Signed in successfully, forward credentials to MongoDB Realm.
    
    let app = App(id: "application-0-fkaqn")
    let id  = googleUser.authentication.idToken
    let credentials = Credentials.googleId(token: googleUser.authentication.idToken)
    
    app.login(credentials: credentials) { result in
        DispatchQueue.main.async {
            switch result {
            case .failure(let error):
                print("Failed to log in to MongoDB Realm: \(error)")
            case .success(let user):
                
                print("Successfully logged in to MongoDB Realm using Google OAuth.")
                
                
                // Now logged in, do something with user
                // Remember to dispatch to main if you are doing anything on the UI thread
            }
        }
    }
}

答案 3 :(得分:0)

我在我的应用中也遇到了与Google登录类似的问题。

这是适合我的解决方案。

斯威夫特3: -

let serverAuth = user.serverAuthCode

if serverAuth != nil {
   //Server auth is received successfully so you can user navigation.
}
else{
    //Here we make the user logout programatically. So now onwards if user clicks log in with google we won't get nil serAuthCode
    GIDSignIn.sharedInstance().signOut()
}

答案 4 :(得分:0)

您必须在didFinishLaunchingWithOptions中的应用程序委托中设置clientId和服务器客户端ID

GIDSignIn.sharedInstance()。clientID =“”

GIDSignIn.sharedInstance()。serverClientID =“”

答案 5 :(得分:0)

很简单。为了获得serverAuthCode,您需要在后端设置serverClientID。

GIDSignIn.sharedInstance()?.serverClientID = "your-server-side-id"