I am working on sign in with apple API in laravel 10. But redirect url is giving this error "The POST method is not supported for route auth/apple/callback. Supported methods: GET, HEAD".
I am using get method on route. I also tried "POST" method but then it give 419 page expired error. I am using ngrok for redirect url as apple does not support http request for redirect url.
These are my routes
Route::middleware(['web'])->group(function () {
Route::get('auth/apple', [AppleLoginController::class,'redirectToApple']);
Route::get('auth/apple/callback', [AppleLoginController::class,'handleAppleCallback']);
});
And these are controller methods
public function redirectToApple()
{
return Socialite::driver('apple')->redirect();
}
public function handleAppleCallback()
{
try {
$appleUser = Socialite::driver('apple')->user();
$user = User::where('apple_id', $appleUser->id)->orWhere('email', $appleUser->email)->first();
// If the user doesn't exist, create a new user
$uuid = Uuid::uuid4();
if (!$user) {
$new_user = User::updateOrCreate(['email' => $appleUser->email], [
'name' => $appleUser->name,
'apple_id' =>$appleUser->id,
'u_id' => substr($uuid->toString(), 0, 16),
'password' => encrypt(Str::random())
]);
}
Auth::login($new_user ?? $user);
event(new Registered($new_user));
return response()->success("Login Successfull");
} catch (InvalidStateException $e) {
return response()->error($e->getMessage(), 'Apple Sign-In Failed');
}
}
This is redirect url in .env file
APPLE_REDIRECT_URI=https://f41e-2407-d000-d-25ae-70b2-4bc-d133-5396.ngrok-free.app/auth/apple/callback
You have to make the callback route auth/apple/callback
support the POST method.
As you mentioned, you will run into issues with CSRF verification. To get around this, you will have to exclude your route from CSRF verification in app/Http/Middleware/VerifyCsrfToken.php
using the except
property.
For example:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
"auth/apple/callback"
];
}