DEV Community

AL Mamon
AL Mamon

Posted on

Implementing Sign in with Apple in Laravel REST API

To implement Sign in with Apple functionality in your Laravel REST API, you'll need to follow these steps:

  1. Prerequisites

    An Apple Developer account

    A registered app in Apple Developer portal

    Laravel 8.x or higher

    PHP 7.4 or higher

  2. Setup Apple Developer Configuration

    Go to Apple Developer Portal

    Create a new App ID with "Sign In with Apple" capability enabled

    Note your Service ID (e.g., com.example.app)

    Generate a private key for "Sign In with Apple" and download it

  3. Install Required Packages

composer require laravel/socialite
composer require socialiteproviders/apple
Enter fullscreen mode Exit fullscreen mode
  1. Configuration

Add these to your .env file:

APPLE_CLIENT_ID=nz.co.fskills.app
APPLE_TEAM_ID=J43F88Y4BH
APPLE_KEY_ID=CLU5NYTK5P
APPLE_PRIVATE_KEY_PATH=storage/apple_private_key.pem
Enter fullscreen mode Exit fullscreen mode

config/services.php

'apple' => [
  'client_id' => env('APPLE_CLIENT_ID'),
  'client_secret' => env('APPLE_CLIENT_SECRET'),
  'redirect' => env('APPLE_REDIRECT_URI')
],
Enter fullscreen mode Exit fullscreen mode

Store the apple_private_key.pem in storage/apple_private_key.pem

-----BEGIN PRIVATE KEY-----
Example key
-----END PRIVATE KEY-----
Enter fullscreen mode Exit fullscreen mode

Create an Controller :

public function SocialLogin(Request $request): \Illuminate\Http\JsonResponse
    {

        $request->validate([
            'token'    => 'required',
            'provider' => 'required|in:google,facebook,apple',
        ]);

        try {
            $provider   = $request->provider;
            $socialUser = Socialite::driver($provider)->stateless()->userFromToken($request->token);
            //return response()->json($socialUser);

            if ($socialUser) {
                $user      = User::withTrashed()->where('email', $socialUser->email)->first();
                if (!empty($user->deleted_at)) {
                    return Helper::jsonErrorResponse('Your account has been deleted.',410);
                }
                $isNewUser = false;

                if (!$user) {
                    $password = Str::random(16);
                    $user     = User::create([
                        'name'              => $socialUser->getName(),
                        'email'             => $socialUser->getEmail(),
                        'password'          => bcrypt($password),
                        'avatar'             => $socialUser->getAvatar(),
                        'email_verified_at' => now(),
                    ]);
                    $isNewUser = true;
                }

                Auth::login($user);
                $token = auth('api')->login($user);

                return response()->json([
                    'status'     => true,
                    'message'    => 'User logged in successfully.',
                    'code'       => 200,
                    'token_type' => 'bearer',
                    'token'      => $token,
                    'expires_in' => auth('api')->factory()->getTTL() * 60,
                    'data'       => $user,
                ],200);
            } else {
                return Helper::jsonResponse(false, 'Unauthorized', 401);
            }
        } catch (Exception $e) {
            return Helper::jsonResponse(false, 'Something went wrong', 500, ['error' => $e->getMessage()]);
        }
    }

Enter fullscreen mode Exit fullscreen mode

Create a route:

Route::post('/social-login', [SocialLoginController::class, 'SocialLogin']);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)