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!