使用Apple登录:在服务器端验证令牌

时间:2020-06-18 19:31:49

标签: ruby-on-rails ruby omniauth apple-sign-in

嗨,我正在尝试验证客户端应用程序在服务器端提供的apple auth凭据,我正在从客户端获取以下字段:authorizationCodeidentityToken和一个很多其他领域。

我尝试阅读很多博客,但是没有一个博客提到这些领域。通过将这些字段用于某些Apple API来验证和获取用户详细信息的最简单方法是什么

对于Google,我已经做到了,客户端将访问令牌传递给后端,并使用https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=YourToken来验证令牌并获取用户详细信息。

请为苹果建议类似的方法。谢谢。 如果有帮助,我正在使用ROR。

2 个答案:

答案 0 :(得分:2)

最后,我能够弄清楚如何验证从客户端收到的访问令牌。 Apple没有提供任何用于验证访问令牌的API,我强烈推荐this blog,它可以整洁地说明整个过程。 This is the ruby code link for the same

答案 1 :(得分:1)

对于那些需要React-Native客户端代码的人,请参见以下内容:

import * as React from 'react';
import * as AppleAuthentication from 'expo-apple-authentication';
import { signInWithApple } from '../api';

const AppleAuthenticationButton = () => (
  <AppleAuthentication.AppleAuthenticationButton
    buttonType={AppleAuthentication.AppleAuthenticationButtonType.SIGN_IN}
    buttonStyle={AppleAuthentication.AppleAuthenticationButtonStyle.WHITE}
    cornerRadius={5}
    style={{ width: 200, height: 44 }}
    onPress={async () => {
      try {
        const credential = await AppleAuthentication.signInAsync({
          requestedScopes: [
            AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
            AppleAuthentication.AppleAuthenticationScope.EMAIL,
          ],
        });

        console.log('signed in', credential);
        await signInWithApple(credential);
        // signed in
      } catch (e) {
        if (e.code === 'ERR_CANCELED') {
          console.log('cancelled');
          // handle that the user canceled the sign-in flow
        } else {
          console.log('apple authentication error', e);
          // handle other errors
        }
      }
    }}
  />
);

export default AppleAuthenticationButton;
export const signInWithApple = async (credentials) => {
  const {
    identityToken, user, email, authorizationCode, fullName,
  } = credentials;

  apiCall('users/sign_in', 'post', {
    method: 'apple',
    identityToken,
    user,
    email,
    authorizationCode,
    fullName,
  });
};

此外,正如我在下面的评论中指出的那样,我发现Apple凭据提供了2个密钥,只有其中一个可以使用。我不知道为什么,但是下面的代码比以前的响应中链接的代码更好。

  def validate_apple_id

    name = params[:name]
    userIdentity = params[:user]
    jwt = params[:identityToken]

    begin
      header_segment = JSON.parse(Base64.decode64(jwt.split(".").first))
      alg = header_segment["alg"]

      apple_response = Net::HTTP.get(URI.parse(APPLE_PEM_URL))
      apple_certificate = JSON.parse(apple_response)
      token_data = nil

      apple_certificate["keys"].each do | key |
        keyHash = ActiveSupport::HashWithIndifferentAccess.new(key)
        jwk = JWT::JWK.import(keyHash)
        token_data ||= JWT.decode(jwt, jwk.public_key, true, {algorithm: alg})[0] rescue nil
      end

      if token_data&.has_key?("sub") && token_data.has_key?("email") && userIdentity == token_data["sub"]
        yield
      else
        # TODO: Render error to app
      end
    rescue StandardError => e
      # TODO: Render error to app
    end

  end