Note: Before diving into this implementation, consider that there are more popular and potentially easier-to-use solutions for implementing Sign in with Apple in Ruby on Rails, such as Omniauth. If you prefer a more out-of-the-box approach, explore those alternatives.
This implementation of the Sign in with Apple service in Ruby on Rails is suitable for APIs, eliminating the need for views.
This implementation handles the following tasks:
-
Identity Token Verification:
- Verifies the user's identity token with Apple servers.
- Ensures the token is not expired and has not been tampered with or replayed to the app.
-
User Authentication:
- Logs in the user.
- Registers the user.
- Connects the user's Apple account to an existing account.
Make use of the following parameters in the implementation:
code
: Apple's authorization code after sign-in. Example:c49a75458b1e74b9f8e866f5a93b1689a.0.nrtuy. ...
id_token
: Apple's identity token after sign-in. Example:eyJraWQiOiJBSURPUEsxIiwiYWxnIjoiUlMyNT ...
The code snippet below demonstrates how errors from Apple's servers are handled:
begin
token_response = @client.access_token!
rescue AppleID::Client::Error => e
# The variable "e" contains the error message from Apple.
return unauthorized
end
This snippet rescues from an ErrorResponse received from Apple, typically due to an invalid value in the code
parameter.
This error may occur under the following circumstances:
- The
code
parameter is invalid. - Changes in Sign in with Apple’s configurations (identifier, private key, team, key id, redirect URI, etc.).
- Mismatch between the backend's configuration making the request to Apple servers (this implementation) and the configuration used in the frontend to display the Sign-in page.
This gist is licensed under the MIT License.
Is it necessary to validate if code parameter is valid? I have the JWT id_token and i verify it using apple key from https://appleid.apple.com/auth/keys