Вход в Google с использованием AppAuth и идентификатора клиента

Я использую AppAuth реализовать вход в Google. Приложение может успешно пройти проверку подлинности. Но мне нужно id_token для моего сервера, чтобы я мог общаться с моим сервером из моего приложения. Для этого я считаю, что мне нужно включить audience:server:client_id:WEB_CLIENT_ID как показано в следующей ссылке.

https://developers.google.com/identity/sign-in/android/v1/backend-auth

Дополнительная информация доступна здесь: https://developers.google.com/identity/protocols/CrossClientAuth

Как я могу использовать свой идентификатор веб-клиента из приложения, чтобы получить id_token, чтобы я мог надежно общаться с моим сервером, используя этот токен?

1 ответ

Решение

Сфера audience:server:client_id:WEB_CLIENT_ID специфично для Android, За iOS нам нужно отправить audience=WEB_CLIENT_ID в качестве параметра для конечной точки токена.

Это работает в моем случае, используя следующий код.

OIDServiceConfiguration *configuration = [[OIDServiceConfiguration alloc] initWithAuthorizationEndpoint:authorizationEndpoint tokenEndpoint:tokenEndpoint];

// builds authentication request
OIDAuthorizationRequest *authorizationRequest =
[[OIDAuthorizationRequest alloc] initWithConfiguration:configuration
                                              clientId:kClientId
                                                scopes:@[OIDScopeOpenID,
                                                         OIDScopeEmail]
                                           redirectURL:[NSURL URLWithString:kRedirectUri]
                                          responseType:OIDResponseTypeCode
                                  additionalParameters:nil];

// performs authentication request
OIDAuthorizationUICoordinatorIOS *coordinator = [[OIDAuthorizationUICoordinatorIOS alloc]
                                                 initWithPresentingViewController:self];
id<OIDAuthorizationFlowSession> authFlowSession = [OIDAuthorizationService
                                                   presentAuthorizationRequest:authorizationRequest
                                                   UICoordinator:coordinator
                                                   callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
                                                              NSError *_Nullable authorizationError) {
                                                       // inspects response and processes further if needed (e.g. authorization
                                                       // code exchange)
                                                       if (authorizationResponse) {
                                                           if ([authorizationRequest.responseType
                                                                isEqualToString:OIDResponseTypeCode]) {
                                                               // if the request is for the code flow (NB. not hybrid), assumes the
                                                               // code is intended for this client, and performs the authorization
                                                               // code exchange

                                                               OIDTokenRequest *tokenExchangeRequest =
                                                               [[OIDTokenRequest alloc] initWithConfiguration:authorizationRequest.configuration
                                                                                                    grantType:OIDGrantTypeAuthorizationCode
                                                                                            authorizationCode:authorizationResponse.authorizationCode
                                                                                                  redirectURL:authorizationRequest.redirectURL
                                                                                                     clientID:authorizationRequest.clientID
                                                                                                 clientSecret:authorizationRequest.clientSecret

                                                                                                       scope:authorizationRequest.scope
                                                                                                 refreshToken:nil
                                                                                                 codeVerifier:authorizationRequest.codeVerifier
                                                                                         additionalParameters:@{@"audience":kWebClientId}];
                                                               //tokenExchangeRequest.scope = kAudienceServerClientId;

                                                               [OIDAuthorizationService
                                                                performTokenRequest:tokenExchangeRequest
                                                                callback:^(OIDTokenResponse *_Nullable tokenResponse,
                                                                           NSError *_Nullable tokenError) {
                                                                    OIDAuthState *authState;
                                                                    if (tokenResponse) {
                                                                        authState = [[OIDAuthState alloc]
                                                                                     initWithAuthorizationResponse:
                                                                                     authorizationResponse
                                                                                     tokenResponse:tokenResponse];
                                                                    }

                                                                    [self onSignInResponse:authState error:tokenError];
                                                                }];
                                                           } else {
                                                               // implicit or hybrid flow (hybrid flow assumes code is not for this
                                                               // client)
                                                               OIDAuthState *authState = [[OIDAuthState alloc]
                                                                                          initWithAuthorizationResponse:authorizationResponse];

                                                               [self onSignInResponse:authState error:authorizationError];
                                                           }
                                                       } else {
                                                           [self onSignInResponse:nil error:authorizationError];
                                                       }
                                                   }];

MyAppDelegate *appDelegate = [MyAppDelegate sharedInstance];
appDelegate.currentAuthorizationFlow = authFlowSession;
Другие вопросы по тегам