Получить адрес электронной почты при входе в систему, используя GTMOAuth2
Я использую GTMOAuth2 для входа на iOS с моим корпоративным приложением. Сценарий - только пользователи с учетной записью @mycompanyname.com могут войти в систему.
Проблема в том, что я вызываю метод, предоставленный в документации, но я не могу получить учетную запись электронной почты пользователя, которую он использовал для входа.
Звонок на вход производится следующим образом:
_auth = [self authForGoogle];
// Display the authentication view
GTMOAuth2ViewControllerTouch * viewController = [[GTMOAuth2ViewControllerTouch alloc] initWithAuthentication:_auth
authorizationURL:[NSURL URLWithString:GoogleAuthURL]
keychainItemName:@"GoogleKeychainName"
delegate:self
finishedSelector:@selector(viewController:finishedWithAuth:error:)];
[_window setRootViewController: viewController];
[_window makeKeyAndVisible];
В моем методе делегата GTMOAuth2 я сделал это, чтобы попытаться получить адрес электронной почты:
- (void)viewController:(GTMOAuth2ViewControllerTouch * )viewController
finishedWithAuth:(GTMOAuth2Authentication * )auth
error:(NSError * )error
{
if ([[_auth userEmail] rangeOfString:@"@mycompanyname.com"].location == NSNotFound && error != nil ) {
// Loop for no mycompanyname mail domain and also error in login
NSLog(@"Loop 1 - Non mycompanyname domain email OR Google login error.");
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"Please Login with your mycompanyname email."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
} else if ([[_auth userEmail] rangeOfString:@"@mycompanyname.com"].location == NSNotFound) {
// Loop for no error in login but without mycompanyname mail domain
NSLog(@"Loop 2 - Non mycompanyname domain email AND no Google login error.");
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Authentication Denied"
message:@"Please Login with your mycompanyname email."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
} else if (error != nil) {
NSLog(@"Loop 3 - mycompanyname domain email AND Google login error.");
if ([[error localizedDescription] rangeOfString:@"error -1000"].location != NSNotFound)
{
NSLog(@"Loop 3.1 - Error message contains 'error -1000'.");
// Loop to catch unwanted error message from GTMOAuth which will show if user enters the app and decides not to sign in but enters the app after again.
} else
{
// Loop for error in authentication of user for google account
NSLog(@"Loop 3.2 - Error message caused by no internet connection.");
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"Your internet connection seems to be lost."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
} else {
// Loop for mycompanyname mail domain and no authentication error
NSLog(@"Loop 4 - mycompanyname domain email AND no Google login error.");
// initialize app
}
}
Проблема в том, что я не могу получить правильный адрес электронной почты пользователя, который пытается войти, чтобы иметь возможность точно проверить адрес электронной почты и только инициализировать приложение после.
Я проверил ошибки и все использовал адрес @ gmail.com для входа в систему, что объясняет, почему коды длинные.
Пожалуйста помоги! Заранее спасибо!
2 ответа
Я столкнулся с точно такой же проблемой!
После долгих часов просмотра кодов GTMOAuth2, регистрации всего и отслеживания методов, которые были вызваны по пути, мне удалось заставить его работать!
В конечном итоге, чтобы получить адрес электронной почты, я взломал класс GoogleOAuth GTMOAuth2SignIn.m по методу:
- (void)auth:(GTMOAuth2Authentication *)auth finishedWithFetcher:(GTMHTTPFetcher *)fetcher error:(NSError *)error
Это связано с тем, что при аутентификации будет отображаться ошибка, в результате которой объект аутентификации не получит значения аутентифицированного пользователя. то есть. не тянет адрес электронной почты пользователя.
Поэтому я добавил строку в метод, и теперь он выглядит так:
- (void)auth:(GTMOAuth2Authentication *)auth finishedWithFetcher:(GTMHTTPFetcher*)fetcher error:(NSError *)error
{
self.pendingFetcher = nil;
#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT
if (error == nil && (self.shouldFetchGoogleUserEmail || self.shouldFetchGoogleUserProfile) && [self.authentication.serviceProvider isEqual:kGTMOAuth2ServiceProviderGoogle]) {
// fetch the user's information from the Google server
[self fetchGoogleUserInfo];
} else {
// we're not authorizing with Google, so we're done
/**** CHANGED HERE TO CALL THE FETCH METHOD NO MATTER WHAT SO THAT THE EMAIL CAN BE SHOWN *****/
[self fetchGoogleUserInfo];
/**********************************************************************************************/
//[self finishSignInWithError:error]; // comment this out so that it will it will initiate a successful login
}
#else
[self finishSignInWithError:error];
#endif
}
После этого я использовал тот же звонок
[_auth userEmail]
и смог получить адрес электронной почты аутентифицированного пользователя.
Это была долгая, мучительная и напряженная отладка для меня, так что я надеюсь, что это сэкономило вам время и кучу волос!:)
Попробуй это.,,,
- (void)signInWithGoogle:(id)sender
{
GTMOAuth2Authentication * auth = [self authForGoogle];
NSString * googleAuthURL = @"https://accounts.google.com/o/oauth2/auth";
GTMOAuth2ViewControllerTouch * viewController = [[GTMOAuth2ViewControllerTouch alloc]
initWithAuthentication:auth
authorizationURL:[NSURL URLWithString:googleAuthURL]
keychainItemName:@"GoogleKeychainName"
completionHandler:^(GTMOAuth2ViewControllerTouch *viewController,
GTMOAuth2Authentication *auth, NSError *error) {
if (error != nil)
{
//error
}
else
{
googleAuth = auth;
NSMutableDictionary * parameters = auth.parameters;
NSString * email = [parameters objectForKey:@"email"];
}
}];
}
}
-(GTMOAuth2Authentication *) authForGoogle
{
NSString * googleTokenURL = token;
NSString * googleClientID = client id;
NSString * googleClientSecret = client secret;
NSString * redirectURI = redirect uri;
NSURL * tokenURL = [NSURL URLWithString:googleTokenURL];
GTMOAuth2Authentication * auth ;
auth = [GTMOAuth2Authentication authenticationWithServiceProvider:@"Google"
tokenURL:tokenURL
redirectURI:redirectURI
clientID:googleClientID
clientSecret:googleClientSecret
];
auth.scope = scope;
return auth;
}