Laravel Sanctum: Your Secret Weapon for API Security! 🚀🛡️
Greetings, Code Warriors! 🤓
How it Works? 🤔
Imagine a superhero squad where every member has their unique token. That’s Laravel Sanctum! It securely authenticates your API using tokens instead of passwords. Now, who needs Batman when you can protect your app like Batman?!
Installation 🛠️
Adding Sanctum to your Laravel project is as easy as saying “Avengers, assemble!” Just follow these simple steps and boom! Your app is more secure than Fort Knox! 😉
Configuration 💡
Customization is the name of the game here. You can change the default models to fit your app like a glove. Because who wants a one-size-fits-all superhero suit, right? 🕺️
Overriding Default Models 🤹♂️
Think of it as picking your favorite Batman suit from the Batcave. You can customize which models Sanctum uses, making your app more personalized than Joker’s clown car! 🎪
API Token Authentication 🔑
This is where the real superpowers come into play! Issue API tokens, manage their abilities, protect your routes, revoke them if needed, and even set expiration times. It’s like having a team of Robin, Batgirl, and Nightwing at your service! 🦸♂️🦸♀️🦸♂️
Issuing API Tokens 💥
Issue tokens like Batman issues his Batarangs! With a few lines of code, you can create new tokens to empower your users. Just remember, with great power comes great responsibility! ⚡️
Token Abilities 🦸♂️🦸♀️
Define the abilities of each token based on their mission. Some might have read and write access, while others are limited to reading only. It’s like having a team with specific roles - Alfred for administration, Batman for action, and Robin for support! 🏰
Protecting Routes 🛡️
Guard your application like the Gotham City Police Department guards Gotham. Use middleware to protect your routes from unwanted intruders. With Sanctum, you’re as safe as a fortress built by Lex Luthor! 🏰
Revoking Tokens 🚫
Revoke tokens when they are no longer needed or compromised. It’s like disabling Batman’s Batsuit when he’s in Arkham Asylum for a good night’s sleep! 😉
Token Expiration ⏰
Set token expiration times to keep your app secure. With tokens that self-destruct, you can sleep like a baby knowing your data is safe from the Joker’s prying eyes! 😴
SPA Authentication 🕺️
For Single Page Applications (SPAs), we’ve got you covered too! Configure, authenticate, protect routes, and authorize private broadcast channels. It’s like having a utility belt full of tools for your superhero adventures! 🧪
Configuration 📝
Set up Sanctum for your SPA with just a few simple steps. It’s as easy as getting a Batmobile ready for a mission! 🚗
Authenticating 🦸♂️🦸♀️
Authenticate users and manage their sessions. With Sanctum, you’re providing your users with a secure Batcave for their digital identities! 🏰
Protecting Routes 🛡️
Guard your SPA routes like the GCPD guards the streets of Gotham. Use middleware to protect your pages from unwanted intruders. With Sanctum, you’re as safe as Batman and Robin on patrol! 🦸♂️🦸♀️
Authorizing Private Broadcast Channels 📣
Authorize private broadcast channels for secure, real-time communication. It’s like having a Bat-Signal for your users to communicate with each other! 💬
Mobile Application Authentication 📱
For mobile applications, we’ve got you covered too! Issue API tokens, protect your routes, and revoke them if needed. It’s like having a Bat-Signal for your app users! 💫
Issuing Mobile API Tokens 📱
Issue tokens tailored to mobile applications. With Sanctum, you’re providing your users with a secure Batcave for their mobile identities! 🏰
Protecting Mobile API Routes 🛡️
Guard your mobile API routes like the GCPD guards the streets of Gotham. Use middleware to protect your routes from unwanted intruders. With Sanctum, you’re as safe as Batman on patrol! 🦸♂️
Revoking Mobile API Tokens 🚫
Revoke tokens when they are no longer needed or compromised. It’s like disabling Batman’s Batsuit when he’s in Arkham Asylum for a good night’s sleep! 😉
Testing 🧪
Test your app like Bruce Wayne tests his new gadgets. Sanctum comes with built-in testing capabilities, so you can ensure that your app is as secure as Fort Knox! 🛡️
Hullo there, web wanderers!
Meet Laravel Sanctum - your new bestie for securing single page apps (SPAs), mobile apps, and token-based APIs that are as cool as a cucumber on a hot summer’s day! It’s the featherweight champion you’ve been waiting for.
Wondering how it works? Fear not, dear friend! Sanctum lets each user of your swanky app create multiple API tokens like they were ordering appetizers at a fancy restaurant. And just like those tasty treats, these tokens can be given abilities or ‘scopes’ that dictate the naughty or nice things they can do.
So, grab a virtual margarita (we’re all about keeping it classy) and dive into the world of secure APIs, where your data is safe as Fort Knox and almost as fun! 🥳💪✨
Alright, buckle up, tech wizards! We’re about to embark on a thrilling journey through the magical realm of Laravel Sanctum – the knight in shining armor that swoops in to slay two pesky programming problems with panache and flair.
But first, let’s take a brief detour into the heart of darkness: those annoying coding conundrums we all love to hate.
Problem 1: Securing API Tokens
You know the drill – you’ve got your trusty API, and users flocking to it like bees to a honey pot. But here’s the catch: ensuring those user tokens are as secure as Fort Knox is no picnic! Laravel Sanctum steps in with its secret sauce of authentication goodness, handling the heavy lifting so you can focus on more pressing matters, like how many cups of coffee you can consume in a single day.
Problem 2: Stateless Authentication
Ever had the headache of dealing with sessions that are as persistent as a bad cold? Laravel Sanctum is here to offer some much-needed relief! Our superhero library helps you breeze through stateless authentication, leaving those pesky sessions behind like a pair of ill-fitting shoes. Now, who needs all that baggage?
With that out of the way, let’s dive deeper into the world of Laravel Sanctum and discover how it can make your life as a developer just a little bit easier – or at least, a whole lot more fun!
Hey there, tech wizards! Let’s embark on an exhilarating journey into the realm of Laravel Sanctum – the simplified solution for doling out those mystical API tokens to your users, minus the OAuth chaos that’d make a dragon blush! You see, it’s all inspired by the enchanted “personal access tokens” from platforms like GitHub, the digital Hogwarts of our time.
So imagine this: your user-friendly app has a secret nook where users can summon their own API token with a mere click – just like conjuring up a potion in Potions class! With Sanctum, you’ll be the alchemist brewing and managing those tokens for your very own magical world.
Typically, these tokens have an expiration date longer than the lifespan of a Mayfly, but fear not! Users can revoke them at will with a snap of their fingers (or a simple click, in this case).
Now, how does it work? Sanctum stashes user API tokens in one enchanted database table and verifies incoming HTTP requests by peering into the Authorization header – which should be holding a valid API token.
And just like that, you’ve now brewed your own potion of user authentication! Isn’t programming just like casting spells? 🧙♂️✨
Ahoy there, intrepid developer! Buckle up as we delve into the captivating world of Single Page Application (SPA) Authentication, courtesy of our trusty companion, Laravel’s Sanctum!
Sanctum isn’t just some mystical monk on a quest for enlightenment. Nope! It’s more like Robin Hood, here to ensure your SPAs can chat amicably with a Laravel-powered API, whether they share the same hideout or are off adventuring in a separate one, perhaps crafted with Next.js or Nuxt.
Unlike other knights waving shiny tokens about, Sanctum relies on good old Laravel’s built-in cookie-based session authentication services – imagine him using an oversized key instead of a sword! Generally speaking, Sanctum deftly employs Laravel’s web authentication guard, offering benefits such as CSRF protection, session authentication, and XSS-proof authentication credentials.
But fear not if you’re served an HTTP request without the expected cookie – Sanctum doesn’t panic! Instead, it’ll check the Authorization header for a valid API token.
Now here’s a fun fact: Sanctum is flexible as a contortionist! You can use it exclusively for API token authentication or SPA authentication (or both if you’re feeling adventurous). Using Sanctum doesn’t force you to partake in all its features, so go ahead and pick your own adventure!
Jump to Installation 🏃♂️🔧⛓️
Alrighty then! Let’s get this party started with Laravel Sanctum! 🎉🎈
First things first, you gotta install it. And by install, we don’t mean a fun little dance or a lively game of Twister. We’re talking about good old command-line action:
php artisan install:api
Yes, that’s right! Type that out like a pro and watch your Laravel application transform into a superhero ready to fight off those pesky authentication issues! 🦸♂️
Now, if you fancy using Sanctum for single-page applications (SPAs), then you best head over to the SPA Authentication section of this documentation. Think of it as the secret ingredient that’ll make your SPA tastier than a seven-layer dip at a Super Bowl party! 🥳🍽️
But wait, there’s more! If you want to tinker with the settings, head on over to the Configuration section. It’s like being backstage at a rock concert, where you can tweak knobs and pull levers to your heart’s content! 🎤🎸
Ahoy there! Sailor! Welcome aboard the Laravel Ship of Wonders, where we code like a hurricane and learn like the tides. If you’re here to conquer the seas of overriding default models, buckle up! 🌊⚓️
Overriding Default Models 🦄🎩
If you’re feeling rebellious and want to rewrite the rules on our default models, we got you covered! You can override ‘em like a rockstar at a heavy metal concert. Here’s how:
-
Navigate to your project’s
app/Providersdirectory and open theAppServiceProvider. This is the gatekeeper of your Laravel kingdom, where the magic happens. -
Find the
boot()method – this is where you can declare what should happen when your application boots up (which is pretty cool, right?). -
In the boot() method, add the following line:
$this->app->bind(Model::class, YourCustomModel::class);
Replace YourCustomModel with your very own model class that extends Laravel’s \Illuminate\Database\Eloquent\Model. Now, whenever Laravel needs a model, it will use your custom one instead of the default! 🤘️🎉
Remember, you’re not just changing the models here – you’re creating a revolution! So, set sail and let the adventure begin. May your code always be as elegant as a pirate’s parrot and as swift as the wind! 🏴☠️🚀
Unleashing Your Inner Model Maestro with Laravel Sanctum! 🎺🤹♂️
Fancy showing off your programming chops and customizing the internal PersonalAccessToken model like a true pro? Go for it, champ! 🎉
Here’s how to rock the house (er… codebase) with your own spin on the default Sanctum model:
use Laravel\Sanctum\PersonalAccessToken as SanctumPersonalAccessToken;
class PersonalAccessToken extends SanctumPersonalAccessToken
{
// ... (fill in those blank lines with your awesome new features!)
}
Once you’ve dazzled the crowd, you can teach Laravel Sanctum to groove along with your custom model by employing a cunning little method called usePersonalAccessTokenModel. And where do you find this enchanting technique? Why, it lives in the boot function of your application’s AppServiceProvider file! 🕺️
use App\Models\Sanctum\PersonalAccessToken;
use Laravel\Sanctum\Sanctum;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class); // (mic drop)
}
And there you have it! Now, Sanctum will be as smooth as silk when spinning your customized PersonalAccessToken. Just make sure to call this method within the boot function for that perfect integration. 💃🕺️🎉
Alrighty then! Buckle up, coders! It’s time to dive into the world of API Token Authentication – where keys open more than just doors. 🤔
🚨 Attention all developers:
Before we get started, a friendly reminder: API tokens ain’t for securing your own one-of-a-kind Single Page Applications (SPA). That’s reserved for Sanctum’s swanky SPA authentication features! So, if you’re building an app to rule them all, better stick with the big guns.
Now, let’s get down to business – issuing API tokens! 🎟️
First things first: You need to create a Personal Access Token (PAT) for users. Think of it as your secret handshake that lets you access protected areas without all the formalities.
To do this, hop over to the user’s show page and generate a new token. Remember, once you’ve seen one token, they all look the same – don’t lose ‘em! 🔑
With your shiny new PAT in hand, it’s time to authenticate your requests:
// In your HTTP header
Authorization: Bearer {your-token-here}
And that’s a wrap! You’ve now officially joined the elite club of API token holders. Just remember – with great power comes great responsibility (and potential data access). So, keep those tokens safe and secure! 🛡️🔒
Alrighty, buckle up for a rollercoaster ride into the world of API token-tastic fun times! 🎢🤩
With Sanctum at your command, you can now issue those nifty API tokens/personal access tokens (PATs) that’ll authenticate your pet API requests to your shiny new app. Just remember to include the token in the Authorization header, wrapped up as a stylish Bearer token.
Ready to start issuing tokens for users like a boss? Your User model should don the Laravel\Sanctum\HasApiTokens trait:
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
Now, to create a token worthy of your esteemed userbase, utilize the createToken method. This method whips you up a scrumptious Laravel\Sanctum\NewAccessToken instance. API tokens get SHA-256 hashed before being stored in the ol’ database, but don’t worry – you can still access that juicy plain-text token value using the plainTextToken property of the NewAccessToken instance. Display this to your user like a champ right after the token creation:
use Illuminate\Http\Request;
Route::post('/tokens/create', function (Request $request) {
$token = $request->user()->createToken($request->token_name);
return ['token' => $token->plainTextToken];
});
Feeling curious about all of a user’s tokens? Just use the tokens Eloquent relationship provided by the HasApiTokens trait:
foreach ($user->tokens as $token) {
// ...
}
Now, let’s talk about token abilities! 🦸♂️🦸♀️ You can control what your tokens can and cannot do using token abilities. Add the Laravel\Sanctum\HasAbilities trait to your User model to gain access to the abilities method:
use Laravel\Sanctum\HasAbilities;
class User extends Authenticatable
{
// ...
use HasApiTokens, HasFactory, Notifiable, HasAbilities;
}
Now you can assign abilities to a user using the syncAbilities method:
use Illuminate\Support\Str;
Route::post('/users/{user}/abilities', function (User $user, Request $request) {
$user->syncAbilities($request->abilities);
return ['message' => 'Abilities synchronized'];
});
You can even create custom abilities:
use Illuminate\Support\Str;
$ability = Str::kebab(now()->format('YmdHis')); // generate a unique ability name
Auth::user()->givePermissionTo($ability);
Token Superpowers (or, How to Give your JWT some Extra Pizzazz)
Who doesn’t love a bit of magic in their coding life? With Sanctum, you can infuse your tokens with mystical abilities that serve a role reminiscent of OAuth’s “scopes”. It’s like giving your humble token the keys to the kingdom! Here’s how you can sprinkle some stardust on those access tokens.
Bibbidi-Bobbidi-Boo, behold a new token with powers beyond mortal comprehension!
return $user->createToken('token-name', ['superpower:server_update']);
Now that your token is imbued with its powers, let’s see if it can perform some dazzling deeds when handling incoming requests. Sanctum provides two enchantments to help you out - tokenCan and tokenCant.
If the user's token has acquired the power of 'server:update',
let us begin, my dear friend!
if ($user->tokenCan('superpower:server_update')) {
// ...
}
But beware! If the user's token is forbidden from wielding the power of 'server:update',
tread carefully!
if ($user->tokenCant('superpower:server_update')) {
// ...
}
So, who needs a wand when you have Sanctum and its token abilities? 🔮✨
Alright, buckle up, coding cowboy! Let’s dive into the wild world of Laravel’s Token Ability Middleware - a shining beacon in the murky seas of authentication.
First things first, you gotta define some aliases like best friends at a slumber party in your bootstrap/app.php file:
use Laravel\Sanctum\Http\Middleware\CheckAbilities as CapedCrusader;
use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility as Joker;
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'superpowers' => CapedCrusader::class,
'shenanigans' => Joker::class,
]);
})
Now that our superheroes have names, let’s see them in action! The superpowers middleware can be assigned to a route to verify if the incoming request’s token has all of the listed abilities:
Route::get('/orders', function () {
// Token has both "check-status" and "place-orders" superpowers...
})->middleware(['auth:sanctum', 'superpowers:check-status,place-orders']);
The shenanigans middleware can be assigned to a route to verify if the incoming request’s token has at least one of the listed abilities:
Route::get('/orders', function () {
// Token has the "check-status" or "place-orders" shenanigan...
})->middleware(['auth:sanctum', 'shenanigans:check-status,place-orders']);
Now, go forth and protect your routes from unauthorized requests with these mighty middleware! Remember, it’s not just about security; it’s about adding a little superhero flair to your app! 😎💪🦸♂️🦹♀️
Alrighty, let’s get this party started! If you’re dealing with requests coming from your very own, first-party Single Page Application (SPA) and using Laravel Sanctum’s natty SPA auth, then buckle up, buttercup! The tokenCan method will be your new BFF, always returning a resounding “YAAAS” when you’re in the presence of that familiar, first-party SPA vibe.
But remember, just because the method says “Yes, please!” doesn’t mean you have to let ‘em slide. Your application’s authorization policies are the ultimate gatekeepers, deciding whether the token has been graced with the necessary permissions and whether the user is a VIP guest invited to the action.
Imagine an app that manages servers, where only trusted users with the “server:update” permission get to play server janitor (talk about power tripping!). To make sure only those authorized can pull off the update dance, you’d want to check both conditions:
return $request->user()->id === $server->user_id // Are we the rightful owner?
&& $request->user()->tokenCan('server:update') // Do we have the right moves?
Now, initially, allowing the tokenCan method to be a free-for-all for first-party UI initiated requests might seem like it’s straight out of a wild frat party. But fret not! It’s super handy to always assume an API token is within arm’s reach and ready for inspection via the tokenCan method. With this approach, you can call the tokenCan method in your authorization policies without stressing about whether the request came from your app’s UI or was a sneaky API move by one of your third-party pals.
Cheers to making Laravel auth less boring and more fun! 🍻✨
Alrighty, strap in and buckle up, because we’re about to embark on a wild ride through the world of Laravel authentication! Let’s talk about shielding those precious routes like Fort Knox – but with a whole lot more charm. 😎
You see, when it comes to safeguarding your routes from riffraff and impostors, we suggest you enlist the help of our trusty pal, Sanctum! This guard dog (or rather, authentication guard) ensures that all incoming requests get patted down with a rigorous check for valid credentials. It’s like the bouncer at an exclusive nightclub, but instead of a velvet rope and guest list, it uses stateful, cookie-authenticated requests or API tokens.
But why on earth would you want to enforce authentication within your very own routes/web.php and routes/api.php files using Sanctum, you ask? Well, my dear friend, let me enlighten you! Sanctum will first try to authenticate requests with the traditional Laravel session authentication cookie. If that cookie fails to appear (like a no-show at a wedding), it’ll then resort to checking for a token in the request’s Authorization header. Plus, by authenticating all requests with Sanctum, we can call upon its powerful tokenCan method whenever we need to verify if the currently authenticated user has the proper clearance.
So, are you ready to join the elite squad of Laravel route protectors armed with Sanctum? Let’s give this code a whirl:
use Illuminate\Http\Request;
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');
Just remember, with great power comes great responsibility. So always keep your API tokens safe and secure – they’re the keys to your kingdom! 👑🏰💪
Token Termination Service (TTS)
In the event you need to bid farewell to your tokens, fear not! With the Laravel\Sanctum\HasApiTokens trait’s friendly relationship known as “tokens,” you can easily part ways by deleting them from your database. Here’s how:
// Evict all guests...
$user->tokens()->kickEveryoneOut();
// Escort the token that checked-in at the current event...
$event->currentToken()->getRoomService()?->askForCheckOut();
// Say goodbye to a specific token...
$user->tokens()->find($tokenId)->packUpAndGoHome();
Just in case you’re having trouble managing your guest list and want to set some time limits, the Laravel\Sanctum\HasApiTokens trait also provides a token expiration feature. You can configure it in your config/sanctum.php file:
// Set token lifetime (in minutes)...
'expiration' => env('SANCTUM_TOKEN_LIFETIME', 60),
Now, you can rest easy knowing that even the most stubborn tokens will eventually be shown the door!
Token Timers & Tickles
Well, buckle up, because we’re about to dive into the ticklish world of token expiration! 😜
By default, our Sanctum tokens are as eternal as a cat’s nine lives, only getting zapped back by the graveyard of revoked tokens. But if you fancy setting an expiration date for your API tokens, no problemo! You can do so with a little dance in your application’s sanctum configuration file.
Here comes the boogie:
'expiration' => 525600,
Just set the number of minutes you want those tokens to be valid and voila!
Now, if you’re into personalized token expirations, we’ve got you covered. You can assign a unique expiration time to each token like assigning seats on a bus (but without the uncomfortable body odor). Just drop the expiration time as the third argument in your createToken method.
return $user->createToken(
'token-name', ['*'], now()->plus(weeks: 1)
)->plainTextToken;
If you’ve set an expiration time for your tokens, you might also want to schedule a task to clean up the mess (because nobody likes a cluttered API). Fear not! Sanctum includes a sanctum:prune-expired Artisan command that’s as handy as a Swiss Army knife.
To set up a scheduled task to delete expired tokens, you can do this:
use Illuminate\Support\Facades\Schedule;
Schedule::command('sanctum:prune-expired --hours=24')->daily();
So, there you have it! Now your API tokens will have a bedtime just like the rest of us. Sweet dreams, tokens! 😴💤
SPA Authentication: The Laughably Easy Way! 🚀✨
Welcome to the dance floor of digital delight, where Sanctum struts its stuff as your plus-one for authenticate-a-palooza! 🎉💃
Why you ask? Well, single page applications (SPAs) that chat with a Laravel-powered API need a wingman like Sanctum to help them keep it classy and secure. Whether these SPAs are your API’s long-lost siblings in the code repository or swanky party guests from across town, Sanctum is ready to roll out the red carpet! 🌟
But here’s the twist - unlike other dance partners who insist on sending you tokens, Sanctum prefers a more traditional approach. It uses Laravel’s own cookie-based session authentication services for the ultimate throwback vibe! This means CSRF protection, session authentication, and XSS leakage prevention, all wrapped up in one glamorous package.
🚨 CAUTION: Before you hit the dance floor, ensure your SPA and API share the same top-level domain like a harmonious duet. However, they can still be on different subdomains, just like those awkward yet endearing cousins. Also, remember to send the
Accept: application/jsonheader, and either theRefererorOriginheader with your request.
🎯 Now let’s move on to SPA configuration (aka the dance lesson where you learn the cool steps) 💥🕺️💃!
Alrighty, buckle up, tech cowboy! Let’s gallop into the world of Laravel configuration, where your trusty steed (i.e., your domain) gets saddled and ready for action. 🐎✨
Configuring Your First-Party Domains
First things first: you’ll want to secure your domain like Fort Knox, ensuring only your own kingdom (or website) can play in the sandbox. To do this, open up config/app.php and add your trusted domains to the app-url array, like so:
'app-url' => [
'http://yourwebsite.com',
'https://secure-fortress-of-yourwebsite.com',
],
Configuring Database Connections
Now, let’s tackle the mighty database, the lifeblood of your digital empire! Head on over to config/database.php, where you can add and manage all your connections like a maestro conducting an orchestra of SQL queries. 🎶🎵
Configuring Mail
Oh, hey there! Ever wanted to become the postmaster of the digital west? With Laravel, you can send emails like a seasoned cowpoke! To get started, saunter on over to config/mail.php and configure your mail settings. Be sure to include your SMTP credentials (username and password)—just remember not to lose them in the desert like a wayward tumbleweed!
Configuring Caching
Next up, let’s chat about caching, the secret sauce that keeps your site running smooth as butter. Head to config/cache.php and choose your preferred caching driver (Redis, file system, or even memcached if you’re feeling fancy). Just remember: a well-oiled machine is a happy machine!
Configuring Queues
Lastly, it’s time to tackle the mighty task queue, your digital stablehand that takes care of all those pesky chores so you don’t have to. To configure your queues, wander on over to config/queue.php and set up your connection drivers, connection information, and any other fancy settings you may desire.
And there you have it! With these configurations under your belt, you’re well on your way to taming the Wild West of Laravel development. Yeehaw! 🤠🌵
Alrighty then! Let’s get our Laravel act together and configure those first-party domains like a boss! 🤘
First things first, you gotta decide which URLs your Single Page App (SPA) is gonna hit up when it’s feeling frisky. To do this, you can use the stateful configuration option in your sanctum config file. This setting tells Laravel which domains will enjoy “stateful” authentication with session cookies while hittin’ up your API.
To help you out with setting up your first-party stateful URLs, Sanctum has whipped up two handy functions just for you: Sanctum::currentApplicationUrlWithPort() and Sanctum::currentRequestHost(). The former will grab the current application URL straight from the APP_URL environment variable, while the latter injects a slick little placeholder into the stateful domain list that’ll get replaced with the actual host from the current request. This way, all requests from the same domain will be considered stateful and treated like old pals by Laravel.
[!ATTENTION] If you’re accessing your app via a URL with a port number (
127.0.0.1:8000), remember to include the port number in your domain, or else it might end up feeling lonely and left out of the stateful fun. 🙁
Now that we’ve got our domains all squared away, let’s move on to the sanctum middleware! It’s like the bouncer at the coolest API club in town, making sure only authorized requests get in. But remember, even though it might act tough, it still loves you and just wants what’s best for your app. 💖
Alrighty then! You’ve built your shiny new Single Page Application (SPA), and now it’s time to teach Laravel that this isn’t just some random cat video, but a sophisticated app needing secure authentication. We’re gonna make sure your SPA can play nicely with Laravel’s session cookies, while also letting third-party pals and mobile apps join the party using API tokens.
So, without further ado, let’s get this show on the road! Navigate to your application’s bootstrap/app.php file and call upon the magical powers of the statefulApi middleware method:
->withMiddleware(function (Middleware $middleware): void {
$middleware->statefulApi();
})
Just like that, your SPA is no longer just a cat video, but a well-dressed party guest with an invitation to the Laravel dance floor! Now, let’s talk about CORS and cookies. Since Laravel plays by the rules of Cross-Origin Resource Sharing (CORS), you may need to add some extra header love to your SPA for it to play well with others. But don’t worry, we’ve got your back on that front too! 🎉
Ahoy there, Laravel pirates! Sailing the high seas of web development can be a treacherous voyage, but fear not! We’ve got your back when it comes to Cross-Origin Resource Sharing (CORS) and cookies – the swashbuckling duo that keeps your Single Page Application (SPA) shipshape.
If you’re having trouble authenticating with your pirate app from a separate subdomain, ye be misconfigured yer CORS or session cookie settings! To set things aright, cast anchor and run the config:publish Artisan command to hoist the complete cors configuration file:
php artisan config:publish cors
Next up, make sure your application’s CORS configuration is a-spouting the Access-Control-Allow-Credentials header with a value of True. You can manage this by setting the supports_credentials option to true within your app’s config/cors.php file:
// ...
'options' => array(
'supports_credentials' => true,
// ...
),
// ...
Now, hoist the sails and enable the withCredentials and withXSRFToken options on yer application’s global axios instance. Usually, this should be done in yer resources/js/bootstrap.js file:
// ...
axios.defaults.withCredentials = true;
axios.defaults.withXSRFToken = true;
// ...
Lastly, ensure yer application’s session cookie domain configuration can sail on any subdomain of yer root domain. Make it so by prepending the domain with a leading . in yer app’s config/session.php file:
// ...
'domain' => '.domain.com',
// ...
And there ye have it! With these steps, your Single Page Application will be singing shanties of authenticity and CORS harmony once more. Yarr-rumble on, pirates!
Ahoy there, aspiring web adventurer! Let’s dive into the exhilarating world of Laravel authentication, where your data stays safe as a fortress guarded by dragons!
First up: CSRF Protection (Cross-Site Request Forgery). Ever heard about Pete the Pirate trying to steal a princess’ cookies? CSRF is kind of like that. But with us on board, your web application is secure as Fort Knox against such shenanigans! Just make sure you’ve added {{ csrf_field() }} in your forms and enabled CSRF protection in your app/Http/Middleware/VerifyCsrfToken.php.
Next, we’ve got Authentication Guard. It’s like having a bouncer at the entrance of your web application. They check who’s allowed in and ensure only authorized users can access sensitive areas. To use this powerful guard, simply add the line use Illuminate\Foundation\Auth\AuthenticatesUsers; in your custom user controller (found in app/Http/Controllers), then call $this->autehenticate() wherever you want to enforce authentication.
But what good is a guard without Throttle? This feature makes sure no one tries to brute force their way into your app, limiting the number of login attempts per user and preventing potential attacks. To activate it, just add use Illuminate\Session\Middleware\ThrottleRequests; in your app/Http/Kernel.php.
Lastly, remember to adjust your application URLs by defining them in the .env file or creating an app/Providers/AppServiceProvider.php. It’s like giving your web application a personalized address on the internet!
And there you have it! Now that you know the basics of Laravel authentication, you can create secure and adventurous applications without fear of being pillaged by digital pirates! Happy coding, matey!
Ahoy there! Let’s embark on a thrilling adventure through the seas of CSRF Protection in Laravel Land!
First things first: Your Single Page Application (SPA) needs to don its armor and show some ID at the /sanctum/csrf-cookie ball, to initiate CSRF protection for our fine application. Here’s how you do it, in good old JavaScript:
axios.get('/sanctum/csrf-cookie').then(response => {
// Time to dance the SPA login jig...
});
Now, during this grand entrance, Laravel will bestow upon your SPA a sweet XSRF-TOKEN cookie, chock full of the current CSRF token. This magical trinket needs to be decoded from its URL form and tucked into an X-XSRF-TOKEN header on all subsequent requests. Lucky for us, some swashbuckling HTTP client libraries like Axios and the Angular HttpClient will do this for you (pirate emoji here).
But if your JavaScript sea shanty library doesn’t set sail with this token, you’ll need to hoist the Jolly Roger and manually set the X-XSRF-TOKEN header to match the URL decoded value of the XSRF-TOKEN cookie that our trusty route has set.
Happy Coding! May your Laravel voyages be swift and your SPA’s secure! 🏴☠️🚀
Alrighty, partner! First things first: you gotta flip the switch on Laravel’s CSRF protection, ‘cause no cowboy worth their salt rides into town without it. Once that’s done, saddle up for a POST ride to your application’s saloon door (AKA the /login route).
This /login shindig can be either lassoed manually or roped in by a headless authentication package like Laravel Fortify – think of it as a trusty sidekick that takes care of all the nitty-gritties.
If your login attempt is a hit, you’ll get yourself a shiny session cookie from the Laravel app and be authenticated for all subsequent rounds in the saloon (or routes, if we wanna be technical). Plus, since you’ve already asked the Laravel sheriff for a CSRF-protection cookie at /sanctum/csrf-cookie, your future requests will come prepared with their own protection, as long as your JavaScript horse carries the value of the XSRF-TOKEN cookie in its mane (a.k.a the X-XSRF-TOKEN header).
But watch out for those tumbleweeds! If your cowpoke’s session takes a nap due to inactivity, subsequent requests might receive a 401 or 419 HTTP error response – time to kick ‘em outta the saloon and redirect ‘em back to your SPA’s login page.
[!WARNING] You can definitely write your own
/logindance, but remember to ensure it authenticate the user using Laravel’s standard session-based authentication services (a.k.a the web authentication guard). Typically, this means saddling up with the trusty ol’webauthentication guard.
Now, let’s lasso some more routes! Protecting SPA Routes awaits!
Ahoy there, brave coder! If you’re looking to fortify your digital frontier against unauthorized intrusions, fear not, for we’ve got the perfect recipe for you! 🏰🚀
Shielding Your Pathways
To safeguard your routes like a knight defending his castle, it’s time to don the mighty sanctum armor. You’ll want to bestow this guard upon your API routes residing within the mystical land of routes/api.php. This magic artifact will ensure that all incoming requests have been vetted and are authenticated as either trusted subjects from your Single Page Application or bear a valid API token header, summoning them forth from the far-off lands of third parties:
use Illuminate\Http\Request;
Route::get('/knight', function (Request $request) {
return "Sir " . $request->user()->getName(); // Just like our knightly example! 😜
})->middleware('auth:sanctum');
Now, if you’re hankering to guard your private broadcast channels as well, look no further! Just follow our simple instructions and soon enough, only authenticated users will be able to join in the revelry. 🎉🎧📻
P.S.: Remember to always keep your sanctum armor polished and in good condition, for a well-guarded castle is a happy castle! Happy coding, fellow adventurer! 😎🏰
Unleashing the Power of Private Channels for your SPA!
If you’re tired of sharing your secrets with just anyone, it’s time to lock down those private / presence broadcast channels! To do this, you’ll need to bootstrap a rebellion against the status quo in your application’s bootstrap/app.php file.
First, revolt against the tyranny of the withRouting method by ousting its channels entry. In its place, hail the withBroadcasting method, so you can specify the rebellious middleware for your application’s broadcasting routes:
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
// ...
)
->withBroadcasting(
__DIR__.'/../routes/channels.php',
['prefix' => 'api', 'middleware' => ['api', 'auth:sanctum']],
)
Once you’ve established control, it’s time to send a clear message to Pusher that your broadcasting routes are now under new management. To do this, provide a custom Pusher authorizer when initializing Laravel Echo. This will allow you to configure Pusher to use the axios instance that’s been properly armed for cross-domain requests (CORS and Cookies):
window.Echo = new Echo({
broadcaster: "pusher",
cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
encrypted: true,
key: import.meta.env.VITE_PUSHER_APP_KEY,
authorizer: (channel, options) => {
return {
authorize: (socketId, callback) => {
axios.post('/api/broadcasting/auth', {
socket_id: socketId,
channel_name: channel.name
})
.then(response => {
callback(false, response.data);
})
.catch(error => {
callback(true, error);
});
}
};
},
})
And just like that, you’ve successfully claimed your rights to private broadcast channels! Now go forth and conquer the airwaves with your authenticated secrets!
(P.S. For mobile application authentication details, check out this link)
Alright, buckle up, app dev wizards! Let’s dive into the thrilling world of mobile authentication with Laravel Sanctum. This ain’t your grandma’s cookie-cutter login system; it’s a sleek, modern way to secure those mobile-app-API communications like a boss.
So, you want to authenticate your mobile app’s requests to your API? That’s cooler than a polar bear in an ice cave! The process is reminiscent of a high-stakes covert op, but with way less spy gadgets and more PHP magic. While the basic principle is similar to third-party API authentication, there are some spicy twists when it comes to issuing those API tokens.
Now, let’s talk about that tantalizing topic—issuing mobile API tokens. Picture this: you’re a secret agent receiving your mission-critical gadget from Q (your favorite Laravel Sanctum package). Instead of a wristwatch with lasers or a car that folds in half, you get a sweet, encrypted token to authenticate your app with the API.
To issue these tokens, first, make sure you’ve configured your app’s API authentication guard and created an API key for your mobile application. Then, when your app needs to access the API, it can simply send a request to the /sanctum/token route with its API key—think of it like the secret handshake at a spy convention. The server will then generate a fresh token and return it, allowing your app to continue its covert operations securely!
Happy authentication, secret agents, and may all your APIs be secure and your mobile apps thrive in this wild world of code and secrets. Stay tuned for more Laravel Sanctum adventures!
Unleashing API Tokens (or: The Great Token Extravaganza)
Ready to embark on a thrilling adventure? Buckle up, because we’re about to dive into the world of API tokens!
First things first, let’s create a route that’s akin to a secret handshake between your app and your users’ devices. This handshake involves the user’s email/username, password, and a device nickname (you know, like naming your pet).
Use your favorite PHP incantations, some User models, Http requests, Hash functions, and Validation spells...
Route::post('/sanctum/token', function (Request $request) {
$request->validate([
'email' => 'required|email and not smelling fishy',
'password' => 'required and stronger than your neighbor ‘s',
'device_name' => 'required and should be something your user would recognize, like "Nuno’s iPhone 17" or "Bob’s Talking Toaster"',
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect. Did you accidentally swap your password with a pickle recipe?'],
]);
}
return $user->createToken($request->device_name)->plainTextToken;
});
Now, when your mobile app attempts to log in (with all the charm of a first date), it’ll send a request to this token endpoint. The endpoint will bestow upon the app a shiny new API token, which should be stored on the device and used for making additional API requests:
[!NOTE] When issuing tokens for a mobile app, you can also grant special powers (or abilities) to these tokens. Check out our #token-abilities section for more info on that!
Now that your app is armed with the token, it should pass this secret gem in the Authorization header as a Bearer token, ensuring a secure and magical exchange of information. Happy coding, dear wizard! 🧙♂️💫
Shielding Your Routes Like a Ninja! 🥋
Alrighty, buckle up for this whirlwind tour of route protection in Laravel land! As you may have read in our previous dispatches, guarding your routes with the sanctum authentication badge is like having a ninja on patrol. Here’s how you do it:
Route::get('/user', function (Request $request) {
return $request->user(); // Not just anyone gets to see this, remember? 🤫
})->middleware('auth:sanctum'); // Time for our ninja to spring into action!
Revoking Mobile API Tokens (Like a Boss) 💔
Now, sometimes even the mightiest ninjas need to kick a token out of the dojo. Don’t worry; we’ve got your back with revoking mobile API tokens! Here’s how you can show them the exit:
use Illuminate\Support\Facades\Auth;
Route::post('/logout', function () {
Auth::guard('sanctum')->user()->token()->revoke(); // Bye, Felicia! 👋
});
And just like that, you’ve made sure your routes are secure and your tokens won’t outstay their welcome. Happy ninja-ing! 🥷🏼🚀
Token Tussle! 🥊
Ready to wrestle with those pesky API tokens, issued to your users’ mobile devices? Fear not, for we have a fun-filled solution just for you! 🎉
To create an epic battle zone within the “account settings” section of your web app UI, simply list all tokens with a dashing “Revoke” button beside each one. When a user decides it’s time to part ways, they can click the mighty “Revoke” button, and off goes the token into the database abyss!
Remember, these tokens are not mere mortals—they’re royalty in disguise! To access them, you must wield the Laravel\Sanctum\HasApiTokens trait like a noble knight’s sword:
// Revoke all tokens with a single swoosh...
$user->tokens()->delete();
// If a specific token is causing trouble, revoke it with precision...
$user->tokens()->where('id', $tokenId)->delete();
``
Now, don’t forget to test your token tussling skills! (Jump to Testing section if you dare!) 🌪️🚀
Ahoy there, Captain Coder! Sail through the treacherous waters of Laravel’s testing seas with Sanctum by your side!
When you’re ready to swash your buckle and test some code, don’t forget to hoist the actingAs flag! This nifty method lets you authenticate a user (like old seafaring friends) and assign them some spiffy abilities. Here’s how to do it:
Arrrgh, let's write a test!
Use yer trusty compass (User model), grab the helm (Laravel\Sanctum\Sanctum), and steer that ship towards success:
Ye landlubbers can write tests too!
Grab yer compass (User model), take the helm (Laravel\Sanctum\Sanctum), and sail that ship towards success:
Now, to grant some abilities to their token, you’ll need to provide a list of ‘em. For instance, if your user should be able to view tasks, you’d shove this into the actingAs method:
Sanctum::actingAs(
User::factory()->create(),
['view-tasks'] // Yo ho ho, matey! Abilities for ye token!
);
If ye want to give all abilities to the token, just stick a ’*’ in the ability list:
Sanctum::actingAs(
User::factory()->create(),
['*'] // This makes the token an all-powerful pirate captain!
);
Yarr, now ye can test with confidence, knowing that your user is authenticated and armed to the teeth with abilities! Happy sailing, matey!