Laravel移除邮箱验证路由中Bearer Token需求的方法咨询
Got it, let's sort this out for you. The problem here is that using auth:sanctum forces these routes to require a Bearer Token, which doesn't fit real-world email verification flows—users might click the verification link straight from their email without having an API token active, or when requesting a new verification email, they’re likely using a web session instead of a token-based auth setup.
Here’s how to adjust your routes to remove the Bearer Token dependency while keeping them secure:
1. Update the Verification Resend Route
For the sendVerificationEmail endpoint (which resends the verification link), swap out auth:sanctum for session-based authentication middleware. We’ll also add a throttle to prevent abuse:
Route::post('email/verification-notification', [EmailVerificationController::class, 'sendVerificationEmail']) ->middleware(['web', 'auth', 'throttle:6,1']);
web: Applies Laravel’s web session handling, CSRF protection, and other web-specific middlewareauth: Ensures the user is authenticated via their session (no Bearer Token needed)throttle:6,1: Limits users to 6 resend requests per minute to stop spam
If you need this route to work for both web and API contexts without tokens, you could expand the middleware set, but in most cases, resending verification emails is tied to a logged-in web session.
2. Update the Email Verification Link Route
The verify endpoint doesn’t require user authentication at all—because the link itself includes a signed id and hash that Laravel can validate directly. Replace auth:sanctum with security-focused middleware that checks the link’s validity:
Route::get('verify-email/{id}/{hash}', [EmailVerificationController::class, 'verify']) ->name('verification.verify') ->middleware(['signed', 'throttle:6,1']);
signed: Verifies the URL hasn’t been tampered with (Laravel generates this signed link when sending the initial verification email)throttle:6,1: Prevents repeated, malicious verification attempts
Quick Controller Check
If you’re using Laravel’s built-in VerifiesEmails trait in your controller, you won’t need to change any logic:
- For
sendVerificationEmail, you can still access the authenticated user viaauth()->user()as before (now using session auth instead of Sanctum) - For
verify, the trait automatically handles validating the signedidandhashparameters
That’s all! Your email verification routes will now work as expected—users can click the link from their email without needing a Bearer Token, and requesting a new link will work with a standard web login session.
内容的提问来源于stack exchange,提问作者abdemirza

