Google Sign-In for iOS 사례 연구

소개



iOS에서 Google의 OAuth 인증은 Google Sign-In for iOS이라는 SDK를 사용하면 쉽게 구현할 수 있습니다.
다만, 인증 정보로서 MobileSafari의 캐시를 이용하고 있는 관계로 상태 관리가 복잡한 데다가, 공식의 문서에 쓰여지고 있는 정보는 순서 정도로, 「이런 때에 이런 값이 돌려준다」등의 정보가 없습니다.

그래서 본 기사에서는, 「이런 사양으로 하고 싶지만, 어떻게 하면 좋을까」 합니다.

주로 보안 측면에서 Google이 권장하는 구현이 아닐 수 있습니다.
또한 샘플 코드는 Swift가 아닌 Objective-C로 작성되었습니다.
양해 바랍니다.

사례 1: AppDelegate.m 이외의 위치에 GIDSignInDelegate 메서드를 작성하고 싶습니다.



포기하자. 우선 컴파일러에 화가 난다.
자세한 내용은 여기을 참조하십시오.

그래서, 예를 들어 ViewController로 로그인 후의 처리를 하고 싶은 경우는, 아래와 같이 GIDSignInDelegate의 메소드로부터 Notification를 날리는 것이 좋을 것입니다.
(@"MyNotification"등은 정수화해 봅시다)

AppDelegate.m
- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error
{
    // 取得したユーザーのプロフィールや認証情報など、通知を受け取る側に渡す値を生成する
    NSDictionary * info = @{
                           @"email": user.profile.email,
                           @"error": error
                           };

    // Notificationを飛ばす
    NSNotification * n = [NSNotification notificationWithName:@"MyNotification" object:self userInfo:info];
    [[NSNotificationCenter defaultCenter] postNotification:n];
}

MyViewController.m
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    // Notificationを登録する
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(foo:) name:@"MyNotification" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    // Notificationの登録を解除する
    [[NSNotificationCenter defaultCenter removeObserver:self name:@"MyNotification" object:nil];

    [super viewWillDisappear:animated];
}

- (void)foo:(NSNotification *)n
{
    // サインインが実行された後、Notificationを受け取る処理
    // n.userInfo で通知と一緒に渡された値を取り出すことができる
    [n.userInfo objectForKey:@"email"];
}

사례 2: 불필요한 권한을 요청합니다.



Google Sign-In은 기본적으로 '이메일 주소 보기'와 '사용자 프로필 정보 보기'라는 두 가지 권한을 요청합니다.

범위 정보는 여기 공식 문서 프로필과 전자 메일입니다.

GIDSignIn 인스턴스의 속성shouldFetchBasicProfile을 NO로 설정하면 이러한 권한에 대한 요청이 사라집니다.

YouTube Data API를 사용하기 위해 YouTube 채널 정보만 사용하는 등 이러한 범위가 필요하지 않은 경우가 나올 것입니다.
아래는 Google 계정에 연결된 YouTube 정보만 권한을 요청하도록 하는 구현입니다.
GIDSignIn * signIn = [GIDSignIn sharedInstance];
signIn.scopes = @[
                  @"https://www.googleapis.com/auth/youtube.upload",
                  @"https://www.googleapis.com/auth/youtube.readonly"
                  ];
signIn.shouldFetchBasicProfile = NO;
[signIn signIn];

결론



· · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · ·
뭔가 있으면 수시로 업데이트합니다. 아직 검증하고 싶은 곳도 있네요.

좋은 웹페이지 즐겨찾기