簡體   English   中英

谷歌登錄服務器驗證碼無 iOS?

[英]Google Sign in server auth code nil iOS?

我們讓 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是 null 我們不確定可能出了什么問題。

問題是服務器驗證碼只會在用戶第一次登錄時發送。用戶必須剛剛看到確認屏幕。 在所有后續登錄中,將不會發送服務器驗證碼。 轉到https://security.google.com/settings/security/permissions並刪除您應用的憑據,然后您將獲得服務器身份驗證代碼。

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>

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
            }
        }
    }
}

我的應用程序中的 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()
}

您必須在 didFinishLaunchingWithOptions 的應用程序委托中設置 clientId 和服務器 clientId

GIDSignIn.sharedInstance().clientID = ""

GIDSignIn.sharedInstance().serverClientID = ""

您可以通過閱讀CLIENT_ID 與 SERVER_CLIENT_ID來查看這些差異

這很簡單。 為了獲得 serverAuthCode,您是否需要在后端設置 serverClientID。

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

我只是想發布一個更新的答案來解決這個問題。 我正在使用swift 4.2並且我正在執行以下操作以獲取serverAuthCode

let signInConfig = GIDConfiguration(
    clientID: "YOUR_IOS_CLIENT_ID", 
   serverClientID: "YOUR_SERVER_CLIENT_ID"
)
    
GIDSignIn.sharedInstance.signIn(with: signInConfig, presenting: self) { user, error in
    guard error == nil else { return }
    guard let user = user else { return }
        
    let code = user.serverAuthCode // Send to server
    print("serverAuthCode: \(code)")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM