PHPackages                             mikebronner/laravel-sign-in-with-apple - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. mikebronner/laravel-sign-in-with-apple

ActiveLibrary

mikebronner/laravel-sign-in-with-apple
======================================

Add Apple's new single-signon feature to your site with ease.

12.0.0(1y ago)4796.0k↓28.6%66[1 issues](https://github.com/mikebronner/laravel-sign-in-with-apple/issues)MITPHPPHP ^8.1CI passing

Since Oct 12Pushed 1mo ago6 watchersCompare

[ Source](https://github.com/mikebronner/laravel-sign-in-with-apple)[ Packagist](https://packagist.org/packages/mikebronner/laravel-sign-in-with-apple)[ GitHub Sponsors](https://github.com/mikebronner)[ RSS](/packages/mikebronner-laravel-sign-in-with-apple/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (7)Versions (35)Used By (0)

Sign In With Apple for Laravel
==============================

[](#sign-in-with-apple-for-laravel)

[![repository-open-graph-template](https://user-images.githubusercontent.com/1791050/66706715-21cc0800-eceb-11e9-90b4-0a6ae3dd97b7.png)](https://user-images.githubusercontent.com/1791050/66706715-21cc0800-eceb-11e9-90b4-0a6ae3dd97b7.png)

Supporting This Package
-----------------------

[](#supporting-this-package)

This is an MIT-licensed open source project with its ongoing development made possible by the support of the community. If you'd like to support this, and our other packages, please consider sponsoring us via the button above.

We thank the following sponsors for their generosity, please take a moment to check them out:

- [LIX](https://lix-it.com)

Table of Contents
-----------------

[](#table-of-contents)

- [Requirements](#Requirements)
- [Installation](#Installation)
- [Configuration](#Configuration)
- [Implementation](#Implementation)
    - [Button](#Button)
    - [Controller](#Controller)
- [Testing](#Testing)

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 10.0+
- Socialite 5.0+
- Apple Developer Subscription

### Version Support

[](#version-support)

LaravelPHPPackage10.x8.2+5.x11.x8.2+5.x12.x8.2+5.x13.x8.3+5.x

Installation
------------

[](#installation)

[![siwa-video-cover](https://user-images.githubusercontent.com/1791050/66785970-af4a5c00-ee93-11e9-9470-b42af6f237c9.png)](https://vimeo.com/366353988)

1. Install the composer package:

    ```
    composer require mikebronner/laravel-sign-in-with-apple
    ```

    We also recommend using [geneaLabs/laravel-socialiter](https://github.com/GeneaLabs/laravel-socialiter)to automatically manage user resolution and persistence:

    ```
    composer require genealabs/laravel-socialiter
    ```

Configuration
-------------

[](#configuration)

1. Create an `App ID` for your website () with the following details:
    - Platform: iOS, tvOS, watchOS (I'm unsure if either choice has an effect for web apps)
    - Description: (something like "example.com app id")
    - Bundle ID (Explicit): com.example.id (or something similar)
    - Check "Sign In With Apple"
2. Create a `Service ID` for your website () with the following details:
    - Description: (something like "example.com service id")
    - Identifier: com.example.service (or something similar)
    - Check "Sign In With Apple"
    - Configure "Sign In With Apple":
        - Primary App Id: (select the primary app id created in step 1)
        - Web Domain: example.com (the domain of your web site)
        - Return URLs:  (the route pointing to the callback method in your controller)
        - Click "Save".
        - Click the "Edit" button to edit the details of the "Sign In With Apple" configuration we just created.
        - If you haven't verified the domain yet, download the verification file, upload it to , and then click the "Verify" button.
3. Create a `Private Key` for your website () with the following details:
    - Key Name:
    - Check "Sign In With Apple"
    - Configure "Sign In With Apple":
        - Primary App ID: (select the primary app id created in step 1)
        - Click "Save"
    - Click "Continue"
    - Click "Register"
    - Click "Download"
    - Rename the downloaded file to `key.txt`
4. Create your app's client secret:
    - Install the JWT Gem:

        ```
        sudo gem install jwt
        ```
    - Create a file called `client_secret.rb` to process the private key:

        ```
        require 'jwt'

        key_file = 'key.txt'
        team_id = ''
        client_id = ''
        key_id = ''

        ecdsa_key = OpenSSL::PKey::EC.new IO.read key_file

        headers = {
        'kid' => key_id
        }

        claims = {
            'iss' => team_id,
            'iat' => Time.now.to_i,
            'exp' => Time.now.to_i + 86400*180,
            'aud' => 'https://appleid.apple.com',
            'sub' => client_id,
        }

        token = JWT.encode claims, ecdsa_key, 'ES256', headers

        puts token
        ```
    - Fill in the following fields:

        - `team_id`: This can be found on the top-right corner when logged into your Apple Developer account, right under your name.
        - `client_id`: This is the identifier from the Service Id created in step 2 above, for example com.example.service
        - `key_id`: This is the identifier of the private key created in step 3 above.
    - Save the file and run it from the terminal. It will spit out a JWT which is your client secret, which you will need to add to your `.env` file in the next step.

        ```
        ruby client_secret.rb
        ```

#### Alternative: Generate client\_secret in PHP

[](#alternative-generate-client_secret-in-php)

Instead of using the Ruby script above, you can generate the client secret JWT directly in PHP using this package's built-in helper:

```
use GeneaLabs\LaravelSignInWithApple\Support\ClientSecretGenerator;

// One-off generation
$secret = ClientSecretGenerator::generate(
    teamId: 'YOUR_TEAM_ID',
    clientId: 'com.example.service',
    keyId: 'YOUR_KEY_ID',
    privateKey: file_get_contents(storage_path('keys/apple-auth-key.p8')),
    ttlDays: 180, // Max 180 days
);

// Or use config/env values automatically
$secret = ClientSecretGenerator::fromConfig();
```

You can use an Artisan command or scheduled task to auto-rotate the secret before it expires:

```
// In a scheduled command or service provider
$secret = ClientSecretGenerator::fromConfig(ttlDays: 180);
config(['services.sign_in_with_apple.client_secret' => $secret]);
```

Required env vars for `fromConfig()`:

```
SIGN_IN_WITH_APPLE_TEAM_ID=your-team-id
SIGN_IN_WITH_APPLE_KEY_ID=your-key-id
SIGN_IN_WITH_APPLE_PRIVATE_KEY_PATH=/path/to/key.p8
```

5. Set the necessary environment variables in your `.env` file:

    ```
    APPLE_REDIRECT="/apple/login/controller/callback/action"
    APPLE_CLIENT_ID="your app's service id as registered with Apple"
    APPLE_CLIENT_SECRET="your app's client secret as calculated in step 4"
    ```

    > **Note:** The `APPLE_LOGIN` environment variable has been removed (previously `SIGN_IN_WITH_APPLE_LOGIN`). Login routes should be defined in your application's route files instead. See the [Migration Guide](#MigrationGuide) below if upgrading from an older version.

### Redirect URL Requirements

[](#redirect-url-requirements)

Apple has strict requirements for the redirect (callback) URL:

- **Must use HTTPS** — HTTP is rejected in production. Only `http://localhost` is allowed for local development.
- **Must exactly match** the Return URL registered in your Apple Developer account under Services ID configuration.
- **No query parameters** — Apple will reject URLs with query strings.
- **No fragments** — Hash fragments are not supported.

The package validates your redirect URL at auth initiation and throws an `InvalidRedirectUrlException` with a clear error message if it doesn't meet these requirements.

Common mistakes:

- Using `http://` instead of `https://` in production
- Having a trailing slash mismatch between config and Apple Developer Console
- Forgetting to add the URL to your Services ID in the Apple Developer portal

Implementation
--------------

[](#implementation)

### Button

[](#button)

Add the following blade directive to your login page:

```
@signInWithApple($color, $hasBorder, $type, $borderRadius)
```

ParameterDefinition$colorString, either "black" or "white.$hasBorderBoolean, either `true` or `false`.$typeString, either `"sign-in"` or `"continue"`.$borderRadiusInteger, greater or equal to 0.

### CSRF Exclusion

[](#csrf-exclusion)

Apple sends the authorization response as a **POST** request to your callback URL. This would normally trigger a `419 | Page Expired` (CSRF token mismatch) error. **This package automatically excludes the configured callback route from CSRF verification**, so no additional configuration is required.

This is safe because Apple callbacks are validated via the OAuth `state` parameter, not CSRF tokens. If you need to manually exclude the route for any reason, you can use one of these approaches:

**Option A: Exclude the route in your VerifyCsrfToken middleware** (Laravel 10 and earlier):

```
// app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
    '/apple/callback', // or whatever your callback URL is
];
```

**Option B: Use `withoutMiddleware` on the route** (Laravel 11+):

```
Route::post('/apple/callback', [AppleSigninController::class, 'callback'])
    ->withoutMiddleware([\\Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken::class]);
```

### Controller

[](#controller)

This implementation uses Socialite to get the login credentials. The following is an example implementation of the controller:

```
