ios google登录及后台验证 Sign in with Google(swift)

2,070 阅读2分钟

官方:developers.google.cn/identity/si…

参考:blog.csdn.net/weixin_2663…

ios端

准备

1.在Google控制台创建并获得OAuth Client ID,参考官网和:

blog.csdn.net/weixin_2663…

2.xcode中进行相关配置:

  • Xcode中双击项目,右边选中“Info”→“URL Types”→填写“URL Schemes”;“URL Schemes”来自于 Client ID
Client ID:
24324434242-5452fdxcdksfhwdinhf4r5.apps.googleusercontent.com
→左右颠倒获得→
URL Schemes:
com.googleusercontent.apps.24324434242-5452fdxcdksfhwdinhf4r5

3.依赖

pod 'GoogleSignIn'

代码

启用sign in

1.In your app delegate (AppDelegate.swift), declare that this class implements the GIDSignInDelegate protocol.

AppDelegate.swift

import GoogleSignIn
...
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {

2.In your app delegate's application:didFinishLaunchingWithOptions: method, configure the GIDSignIn shared instance and set the sign-in delegate.

AppDelegate.swift

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  // Initialize sign-in
  GIDSignIn.sharedInstance().clientID = "YOUR_CLIENT_ID"//oauth client id
  GIDSignIn.sharedInstance().delegate = self

  return true
}

3.Implement the application:openURL:options: method of your app delegate. The method should call the handleURL method of the GIDSignIn instance, which will properly handle the URL that your application receives at the end of the authentication process.

AppDelegate.swift

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
  return GIDSignIn.sharedInstance().handle(url)
}
//For your app to run on iOS 8 and older, also implement the deprecated 
//application:openURL:sourceApplication:annotation: method.
func application(_ application: UIApplication,
                 open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
  return GIDSignIn.sharedInstance().handle(url)
}

4.登录回调;In the app delegate, implement the GIDSignInDelegate protocol to handle the sign-in process by defining the following methods:

AppDelegate.swift

func sign(_ signIn: GIDSignIn!, didSignInFor user: 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
  }
  // 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
  // ...
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!,
          withError error: Error!) {
  // Perform any operations when the user disconnects from app here.
  // ...
}

调用sign in

ViewController.swift

import GoogleSignIn
...
override func viewDidLoad() {
  super.viewDidLoad()
  GIDSignIn.sharedInstance()?.presentingViewController = self
  //1.自动触发登录 Automatically sign in the user.
  GIDSignIn.sharedInstance()?.restorePreviousSignIn()
	
	//2.手动触发登录 这里使用自定义button,或者可以用 GIDSignInButton
	button.addTarget(self, action: #selector(googleSignIn()), for: UIControl.Event.touchUpInside)
}

@objc private func gogoleClick(){
	GIDSignIn.sharedInstance()?.signIn()
}

//判断google 登录和登出的状态
if (GIDSignIn.sharedInstance()?.currentUser) != nil {
 //已登录
} else {
 //已经登出
}

后端token验证(java)

官方:developers.google.cn/identity/si…

ios端将token和client Id发送到后台,后台进行验证

public class GoogleIdentity {
    String userId;
    String clientId;
    String identityToken;
}
public class GoogleTokenService {
	private static final HttpTransport transport = new NetHttpTransport();
  private static final JsonFactory jsonFactory = new JacksonFactory();
  public Result verifyToken(GoogleIdentity googleIdentity){
	  try {
		  GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
	        // Specify the CLIENT_ID of the app that accesses the backend:
		      .setAudience(Collections.singletonList(googleIdentity.getClientId()))
	         // Or, if multiple clients access the backend:
	         //.setAudience(Arrays.asList(CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3))
	        .build();
	         // (Receive idTokenString by HTTPS POST)
       GoogleIdToken idToken = verifier.verify(googleIdentity.getIdentityToken());
	       if (idToken != null) {
		         Payload payload = idToken.getPayload();
						 // Print user identifier
	           String userId = payload.getSubject();
	           System.out.println("User ID: " + userId);
						 // Get profile information from payload
	           String email = payload.getEmail();
	           boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
	           String name = (String) payload.get("name");
	           String pictureUrl = (String) payload.get("picture");
	           String locale = (String) payload.get("locale");
	           String familyName = (String) payload.get("family_name");
	           String givenName = (String) payload.get("given_name");

	           // Use or store profile information
	           return Result.success("Google token 有效");
          } else {
            System.out.println("Invalid ID token.");
          }
        } catch (Exception e) {
            return Result.fail("Error while getting Google Sign in user info for token " + e.getMessage());
        }
    }
}