2

I need to authentificate user with Apple Auth in mobile application. I got IdentityToken, User and AuthCode from api request from mobile app.

I need to authentificate user and get its email. My class AppleId always returns: "invalid_client".

Maybe i have some mistakes in my logic?


class AppleId

    URL = 'https://appleid.apple.com/auth/token'
    ISSUER = 'https://appleid.apple.com'
    TEAM_ID = '6Z******38'
    KEY_ID = '33******KP'
    IDENTIFIER = 'ru.k*************on'
    PRIVATE_KEY = <<-PEM
-----BEGIN PRIVATE KEY-----
MIGTA**********z7
-----END PRIVATE KEY-----
PEM

    def initialize
      @private_key = OpenSSL::PKey::EC.new PRIVATE_KEY
    end    

    def authenticate(code)
      make_request(code)
    end

    private 

    def make_request(code) 
      uri = URI.parse(URL) 
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true

      request = Net::HTTP::Post.new(uri.request_uri)

      params =  {
        client_id: IDENTIFIER,
        client_secret: client_secret_jwt,
        code: code,
        grant_type: 'authorization_code' 
       }

       request.set_form_data(params)
       response = http.request(request)
       response.body
    end

    def client_secret_jwt
      jwt = JSON::JWT.new(
        iss: TEAM_ID,
        aud: ISSUER,
        sub: IDENTIFIER,
        iat: Time.now,
        exp: 1.minutes.from_now
      )
      jwt.kid = KEY_ID
      JWT.encode jwt, @private_key, 'ES256'
    end

end

In my Controller:

authCode = params[:auth_code]

AppleId.new.authenticate(authCode)
=> "{\"error\":\"invalid_client\"}"

Mike Havit
  • 21
  • 2
  • There's a [Ruby gem](https://rubygems.org/gems/apple_id) that does this, and its [README](https://github.com/nov/apple_id) includes a link to a [sample Rails project](https://github.com/nov/signin-with-apple) to illustrate how it works. I know that this doesn't directly answer your question, but perhaps this might help you figure out how to solve the issue. **EDIT:** There's also this [gist](https://gist.github.com/nov/993a303aa6badd8447f7b96fb952088e). – GoBusto Dec 27 '19 at 13:00
  • Additionally, whilst it does not deal with Rails specifically, this post might be useful: [Sign in with Apple (iOS App + Backend verification) API returns error “invalid_client”](https://stackoverflow.com/q/57809927/4200092) – GoBusto Dec 27 '19 at 13:10
  • I also had similar problem. Client_id on server should be `ServiceId` not `AppId` – Access Denied Jan 02 '20 at 08:27

0 Answers0