Grand Entrance (a.k.a Introduction)
Welcome to the Ball! (a.k.a Starter Kits)
Want to dive right in? Weโve got a ball gown for that! Our starter kits will have you authenticated faster than Cinderella at the stroke of midnight.
Database Dance Cards (a.k.a Database Considerations)
Before we hit the dance floor, letโs talk about the data. Knowing your database is like knowing the DJโs playlist โ itโll keep the party going smoothly!
The Kingdom Tour (a.k.a Ecosystem Overview)
From princes to peasants, everyoneโs invited! Get familiar with our royal ecosystem and join us in this magical land of Laravel.
Fast Pass to the Ball (a.k.a Authentication Quickstart)
Time to Suit Up (a.k.a Install a Starter Kit)
Don your finest armor, or in this case, run composer install with our starter kit. Youโll be ready for the dance in no time!
Spotting Your Partner (a.k.a Retrieving the Authenticated User)
With a twirl of the skirt and a wink, find out who your dance partner is by grabbing the authenticated user with just a few lines of code.
The Bouncer (a.k.a Protecting Routes)
Keep the riffraff out โ our bouncers are standing by to ensure only the right users access your restricted routes.
Dance-Off Determined by Time (a.k.a Login Throttling)
Donโt let anybody hog the dance floor! Our login throttling feature will keep a fair balance of dancers on the floor, ensuring everyone gets their groove on.
Making Introductions (a.k.a Manually Authenticating Users)
Remembering Faces (a.k.a Remembering Users)
No need to ask for phone numbers โ our kingdom remembers its guests! With cookie-based session support, weโll keep track of your users with ease.
Mixers and Mingling (a.k.a Other Authentication Methods)
Join the royal court and network with other authentication methods like token-based or API-based authentication for a truly unforgettable ball!
The Royal Seal (a.k.a HTTP Basic Authentication)
Passwords in Plain Sight (a.k.a Stateless HTTP Basic Authentication)
Keep things simple with HTTP Basic Authentication, where usernames and passwords are sent unencrypted โ because sometimes, a secret handshake just isnโt enough!
Time to Call it a Night (a.k.a Logging Out)
Kissing the Frog Goodbye (a.k.a Invalidating Sessions on Other Devices)
When the ball ends, donโt forget to log out! Our magical kingdom will invalidate sessions on other devices, ensuring no unwanted guests stick around after the dance.
The Final Test (a.k.a Password Confirmation)
Setting the Rules (a.k.a Configuration)
Enforce your kingdomโs password policy to keep things secure and secretive.
Making a Scene (a.k.a Routing)
Route your users through our magical gates, making sure they follow the rules and confirm their passwords before entering.
The Last Dance (a.k.a Protecting Routes)
Only those who have proven their identity should be allowed to dance. Make sure to protect your password confirmation routes to keep things secure.
Keeping the Castle Secure (a.k.a Adding Custom Guards)
The Kingdomโs Gatekeeper (a.k.a Closure Request Guards)
Add your own custom guards to keep uninvited guests from entering our castle. With a simple closure, you can enforce rules based on any condition.
Building the Royal Family Tree (a.k.a Adding Custom User Providers)
The Blueprint of Power (a.k.a The User Provider Contract)
Lay the foundation for your custom user providers, defining their structure and behavior to suit your kingdomโs needs.
The Bloodline of Royalty (a.k.a The Authenticatable Contract)
Trace back your royal bloodline by implementing the Authenticatable contract โ a bond that ties together all members of the kingdomโs ruling family.
Keeping Secrets Safe (a.k.a Automatic Password Rehashing)
The Royal Seal of Approval (a.k.a Automatic Password Hashing and Salting)
Ensure that all secrets are kept safe with automatic password rehashing, a feature that handles hashing and salting for you โ because sometimes, even the royal family needs help keeping things secure!
Social Mingling (a.k.a Social Authentication)
Making Friends in High Places (a.k.a Using Laravelโs Socialite for Social Authentication)
Expand your kingdomโs reach by adding social media integration โ let guests log in using their favorite platforms and make new friends from all around the land!
Announcing the Royal Ball (a.k.a Events)
The Kingdomโs Biggest News (a.k.a Listening to Laravel Events)
Stay informed on everything happening in our kingdom by listening to events โ you never know when a royal celebration is about to begin!
Greetings, web dev adventurers! ๐โจ
In the mystical realm of web apps, thereโs a magical rite called โlogging inโ that turns your users from humble spectators into mighty masters. But tread with caution, for this spell can be as complex and treacherous as a dragonโs lair! Fear not, for Laravel has conjured up the tools to help you cast this enchantment swiftly, securely, and without breaking a sweat (unless itโs due to excitement, of course).
At the heart of our wizardry lies โguardsโ and โproviders.โ Think of guards as the wise sorcerers who authenticate users for each quest (request). We come equipped with a cunning session guard that uses session storage and cookies to ensure your usersโ identities remain safe and sound.
Providers, on the other hand, are the mighty librarians who fetch users from your ancient scrolls โ er, databases. Laravel has bestowed upon you the power to retrieve users using Eloquent or our trusty database query builder. But remember, this is a choose-your-own-adventure game, so feel free to create additional providers to suit your specific quest!
Your magical auth configuration resides in config/auth.php. This spellbook contains several well-documented incantations for tweaking the behavior of Laravelโs enchantments.
Attention
Guards and providers should not be confused with โrolesโ and โpermissions.โ To learn more about granting magical powers to your users via permissions, please refer to our authorization documentation.
Now that youโve embarked on this journey, itโs time to master the art of authentication and turn your web app into a treasure trove where only authenticated users can play! ๐ฐ๐ฅโจ
Happy coding, magic-makers! ๐ค๐งโโ๏ธ๐งโโ๏ธ๐ฉโ๐๐จโ๐
Lightning-Speed Launch Pads ๐
Ready to blast off with your Laravel journey? Strap in and prepare for lift-off! By installing a Laravel Application Launch Pad into your brand-new Laravel spacecraft, youโll have an authenticated universe explorer faster than you can say โhyperdrive engaged!โ ๐
Fear not if you decide against using a launch pad in your ultimate intergalactic voyage. Installing one serves as an excellent chance to dive headfirst into understanding how Laravelโs authentication systems work within a real-world project. Since our launch pads come equipped with controllers, routes, and views for your convenience, you can poke around the code to learn the ins and outs of Laravelโs stellar authentication features!
๐ง โBut wait,โ I hear you say, โwhat about my database?โ Worry not, fellow starfarer, for our launch pads come with a migration system that ensures your database is ready for takeoff. After running the migration command and blasting off to your local server at /register, or any other URL youโve assigned, your launch pad will handle scaffolding the entire authentication system! ๐๐
Oh, the Joys of Database Shenanigans with Laravel!
First off, letโs give a warm welcome to the default App\Models\User - your new best friend in the app/Models directory. This chap is as slick as they come, all thanks to the magical Eloquent model (check out our docs on that here!). And if youโre not into the whole Eloquent scene? Well, no worries, thereโs always the database authentication provider - think of it like Laravelโs party trick with its super-charged query builder.
If your app has taken a fancy to MongoDB, then by all means, check out their official docs for user authentication (weโre just here to code, not break dance).
Now letโs talk about the database schema for App\Models\User. Keep in mind that when designing the password column, you might want to aim for a lengthier conversation with your attackers - 60 characters should do the trick. But donโt worry if you find yourself falling short, as the included users table migration in fresh Laravel apps has already exceeded this length.
Remember that token for those who just canโt seem to let go? Weโre talking about the remember_token. Itโs a string of 100 characters, nullable, and found in your users (or equivalent) table. If youโve forgotten all about it, donโt worry - weโve already placed it in the default users table migration that comes with new Laravel apps.
Now go forth and build databases, dear developers! Just remember to keep a sense of humor while doing so. After all, who said coding had to be boring?
Welcome, brave developer! Buckle up for a whirlwind tour through Laravelโs amusing authentication ecosystem. Before we dive in, letโs get our bearings straight and discuss each packageโs intended purpose, like an old-timey map guide explaining the local taverns.
First off, imagine youโre at a medieval castle gate, and the knight wants to know who you are before letting you in. In this digital age, thatโs equivalent to a user filling out a login form with their credentials (username and password). If they pass the gate guard (authentication check), the castle steward (application) will store information about the authenticated knight (user) in his chamberโs secret drawer โ the userโs session. A magic amulet (session ID cookie) is then handed to the knightโs horse (browser) so that it can present this token to the castle guards (subsequent requests) and be recognized as the correct knight. Once the amulet arrives, the steward retrieves the knightโs information based on the session ID and considers him as โauthenticated.โ
Now, imagine a remote service that wants to gain access to the castleโs treasury (API). In the middle ages, they would have needed a written letter of introduction. Nowadays, they send an API secret key (token) along with each request. The steward may then cross-reference this token against his secret ledger of valid keys and โauthenticateโ the request as being made by the service associated with that token.
Now, letโs delve into Laravelโs built-in browser authentication services! Youโll find them like a treasure trove in the castleโs armory (Laravelโs package library). These services include:
-
Sanctum: The trusty squire that takes care of handling API authentication, making it easier for remote services to gain access to your kingdom (API) without having to write complex code.
-
Passport: The knight in shining armor โ the most powerful of all services. It handles both session and token-based authentication for both web applications and APIs, leaving no stone unturned when it comes to securing your realm.
-
Breeze: This is the castleโs friendly pageboy who helps you set up a new Laravel project with built-in, easy-to-use authentication and UI components. It saves you from all that backbreaking labor of building everything from scratch!
Ahoy there, brave coder! Sail with us into the shimmering seas of Laravelโs built-in browser authentication services! Buckle up as we embark on an adventure thatโll make your appโs login process smoother than a pirateโs accordion!
These magical features are just a Auth and Session facade away, offering cookie-based authentication for requests hailing from good olโ web browsers. Think of them as your crewmates in the realm of user verification and authentication โ theyโll help you confirm if Jack Sparrow (your users) have entered the right password and authenticate them accordingly!
In addition, these services will stow away essential authentication data in a userโs session like a captainโs log, and issue session cookies quicker than you can say โshiver me timbers!โ A comprehensive guide on how to use these services can be found in this very treasure chest of documentation.
Shipshape Starter Kits
As you might have learned from our seafaring tales, you could manually navigate these authentication services to build your appโs custom pirate-proof fortress. But why row when you can sail faster with a little help from our friends? To make your journey swifter than a speeding marlin, weโve launched some nifty free starter kits thatโll supply a robust, cutting-edge scaffolding for the entire authentication layer. Think of it as having an extra crewmate who knows all the best shortcuts and has a compass that always points true north!
Yarr matey, Laravel is here to make your coding journey smoother than a well-oiled anchor โ so set sail, hoist the Jolly Roger, and letโs conquer those shores together!
Laravelโs API Authentication Shenanigans
When it comes to managing your appโs secrets and verifying those sneaky API requests, Laravelโs got you covered! Weโve cooked up two fabulous packages to help: the granddaddy of them all, Passport, and its svelte younger cousin, Sanctum. But fear not, these arenโt your typical cat-fighting sisters! They can coexist peacefully with Laravelโs built-in cookie-based authentication libraries.
Passport - The OAuth2 Overlord
Passport is like the Captain Kirk of API authentication providers, armed with an arsenal of OAuth2 โgrant typesโ to issue various tokens. Itโs a powerhouse for API authentication, but letโs face it, not every application needs a starship enterprise to manage their authentication process. Some may find its complexity as confusing as the Klingon language. But fear not! We havenโt left you high and dry โ weโve got tutorials on authenticating Single Page Applications (SPAs) and mobile apps using Passport, so check โem out if youโre lost in space!
Sanctum - The New Kid on the Block
With the complexity of OAuth2 weighing heavy on developersโ minds, we decided to create a simpler, more streamlined authentication package that could handle both web requests and API tokens with equal ease. And thus, Laravel Sanctum was born! This is the preferred choice for applications that offer a first-party web UI along with an API, or those that exist separately as a Single Page Application (SPA) or mobile client.
Laravel Sanctum is like your trusty doorman, welcoming guests (and verifying their identities) with a smile. When it receives a request, Sanctum first checks if itโs being served by a session cookie referencing an authenticated session โ think of it as checking the guestโs name on the list. If not, Sanctum looks for an API token in the request โ like when someone mentions theyโre โon the list.โ If all goes well, it authenticates the request with that token. Need more details? Head over to Sanctumโs โhow it worksโ documentation!
So, which package is right for your application? That depends on whether youโre building a galaxy-spanning empire (Passport), or a quaint little bar on the outskirts of the cosmos (Sanctum). But remember, both packages play well with Laravelโs built-in authentication libraries, so donโt be afraid to mix and match! Happy authing, captain!
Alrighty, letโs dive into the world of Laravellandia! ๐
In essence, if your web app is a digital storefront, Laravelโs own baked-in security services will be your trusted bouncers at the entrance. ๐จโ๐ผ๐ฉโ๐ผ
But what if your application is more of a behind-the-scenes API barkeep, serving up drinks to third parties? Then youโve got a choice between Passport or Sanctum, with Sanctum being the chatty mixologist who knows his scopes and abilities like the back of his hand. ๐ธ๐คซ
If youโre building a single-page app (think SPA, not SpongeBob) powered by a Laravel backend, Sanctum is your go-to barman. You can either let him handle your authentication routes himself or bring in the backup bartender, Laravel Fortify, for a fancier, more features-packed service. ๐ฉ๐พ
Passportโs your man when your app needs every feature of the OAuth2 specification to mix its drinks like a pro. ๐ค๐ฅ
And if you want to get this party started post-haste, our application starter kits are just the ticket for setting up a new Laravel application complete with our preferred authentication stack. ๐โจ
Now that weโve covered the basics (and a bit of bar jargon), letโs move on to some advanced mixology techniques: authenticating users. Cheers! ๐ฅ
Authentication Blastoff! ๐
Attention
Buckle up, space cowboy! This section of the docs is all about launching users into your Laravel universe using our snazzy application starter kits. These bad boys come equipped with some swanky UI scaffolding to propel you towards interstellar development speeds without leaving a trail of code debris behind.
But fear not, brave adventurer! If youโre yearning for a more hands-on approach and want to dance directly with Laravelโs authentication systems, weโve got you covered in our documentation on DIY user authentication.
Install a Starter Kit ๐ ๏ธ
To kickstart your journey towards galactic success, letโs set up camp with one of our starter kits. Follow these simple steps to get your kit installed:
-
Clone or download the desired starter kit from the Laravel GitHub repository. If youโre not familiar with how to clone repositories, we recommend brushing up on your Git fu before continuing.
-
Navigate to the starter kit directory. Remember, a change of scenery can be invigorating, so donโt forget to switch directories after cloning or downloading your kit.
-
Create a new Laravel application. To do this, run the following command in your terminal:
composer create-project --prefer-dist laravel/laravel YourAppName. Replace โYourAppNameโ with the name youโd like for your shiny new project. -
Link the starter kit to your Laravel application. To do this, copy the contents of the
resourcesdirectory from your starter kit into the root directory of your Laravel application. And remember to keep that precious cargo safe! -
Update the service provider registration. Open up the
config/app.phpfile and add the service provider for your starter kit to theprovidersarray, like so:'providers' => [ // ...other providers... App\Providers\YourStarterKitServiceProvider::class, ], -
Update the event service provider registration. Open up the
events/EventServiceProvider.phpfile and add the following line to the$listenersproperty:'App\Listeners\YourStarterKitListener', -
Run migrations. Your Laravel application now needs a friendly welcome from your starter kit, so letโs help it settle in by running the necessary database migrations:
php artisan migrate.
And there you have it! Youโve successfully set up your shiny new Laravel project with all the bells and whistles provided by our starter kits. Now that your spaceship is fueled and ready to blast off, letโs continue exploring the cosmos of user authentication together! ๐๐
Fire Up Your Laravel Adventure! ๐๐
Ready to embark on a dazzling journey with Laravel? First things first, letโs set sail with a splendid Laravel Starter Kit! These swanky kits are the perfect jump-off points for infusing your brand-spanking-new app with the sophisticated charm of authentication.
Now that youโve got your captainโs hat on, itโs time to meet your first mate! ๐ค To get acquainted with the authenticated user, just grab their details using the handy tools provided in your new starter kit. Itโs like introducing yourself to the crew after a rousing sea shanty! ๐ต๐
Flying High with Laravel: A Guided Tour for the Authenticated User! ๐ฉ๏ธ๐
After launching your airline from a swanky starter kit and allowing passengers (er, users) to sign up and log in like itโs fashion week, youโll often find yourself in need of interacting with the currently authenticated flyer. When handling incoming requests, fear not! The Auth facadeโs got your back, ready to serve you the current passenger at your request:
use Illuminate\Support\Facades\Auth;
// Time to check-in the authenticated traveler...
$passenger = Auth::user();
// Need their boarding pass number? No problem!
$boardingPass = Auth::id();
But wait, thereโs more! Once a passenger has securely checked in, they become your loyal flying companion for the duration of their journey. You can access them via an Illuminate\Http\Request instance (our new best friend). Just remember, type-hinted classes will automatically join your flight and take their seats in your controller methods:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class FlightController extends Controller
{
/**
* Update the flight information for an existing flight.
*/
public function update(Request $request): RedirectResponse
{
$passenger = $request->user(); // Your co-pilot for this flight!
// ๐ง Headphones on, time to navigate the controls...
return redirect('/flights');
}
}
And now, a special word for those who want to ensure their passenger list is up-to-date before departure:
Checking If Your Passenger List is Ready for Takeoff! โ๏ธ
Worried about making an announcement that your flight is boarding when passengers havenโt checked in yet? No need to panic! To find out whether the current user is authenticated, simply check if Auth::check() returns true. Now you can be sure not to miss anyone on your passenger list:
use Illuminate\Support\Facades\Auth;
if (Auth::check()) {
// All aboard! ๐
} else {
// Quick, let's call the ground crew and delay takeoff! ๐
}
Happy flying! โ๏ธ๐
Alrighty then! Letโs dive into the world of Laravel authentication, where even the most mundane tasks are given a dash of panache.
First off, if youโre curious whether your user has successfully completed the password shindig and is ready to party on your web application, you can use the check method from the ever-so-charming Auth facade. This sly little number will return true if your user is indeed authenticated:
use Illuminate\Support\Facades\Auth;
if (Auth::check()) {
// It's a shindig! The user has arrived... or logged in, whatever.
}
Now hold your horses, partner! Even though you could determine if a user is authenticated using the check method, itโs generally more prudent to use a middleware to make sure that said user has passed muster before being granted access to certain routes / controllers. This way, you can keep your web application as secure as Fort Knox and as friendly as a Vegas casino host. To learn more about this jamboree of authentication protection, check out the documentation on protecting routes.
And that, my friends, is how you keep your web application safe from the riffraff and still make it a swinginโ place to be.
Keeping the Airplane Hangar Locked: Route Security in Laravel Land! ๐๐ฉ๏ธ
Ahoy there, Captain! In this seafaring adventure we call Laravel development, weโve got a swashbuckling feature to help you protect your routes from unruly pirates - yes, I mean unauthenticated users. Enter: Route Middleware! ๐น
These maritime guards (erโฆ middlewares) can be used to ensure only those with the proper captainโs hat and parrot (authenticated users, in laymanโs terms) can access a specific route. Laravel supplies you with a trusty shipmate named auth middleware, which is a fancy nickname for the stalwart Illuminate\Auth\Middleware\Authenticate class.
Since this shipmate comes pre-equipped on our vessel, all you need to do is secure him at your chosen route. Hereโs how you might do that:
// Set sail towards flights! โต๏ธ
Route::get('/flights', function () {
// Only pirates with a parrot on their shoulder can pass through here...
})->middleware('auth');
Now, what happens when an unauthenticated user tries to swab the poop deck (access your route)? Fear not! Theyโll be politely redirected to the nearest tavern for a drink or two, giving them ample time to log in before they can set sail with you again. ๐ป ๐
Redirecting Uninvited Party Crashers
Oh, the joys of being a digital bouncer! When our good friend auth middleware spots an unregistered guest at your Laravel soiree, it politely escorts them to the front doorโthe login dance floor, if you will. But what if you want to change this polite shove into a VIP red-carpet treatment? No problemo, amigo!
Just pop open your applicationโs secret backstage pass, aka bootstrap/app.php, and modify the bouncerโs behavior using the redirectGuestsTo method:
use Illuminate\Http\Request;
->withMiddleware(function (Middleware $middleware): void {
$middleware->redirectGuestsTo('/login'); // For those who like it old school
// For the hipster crowd...
$middleware->redirectGuestsTo(fn (Request $request) => route('login'));
})
Just remember, if you decide to rename your login route, youโll need to update this backstage pass accordingly. Itโs like having a party at someone elseโs houseโyou gotta respect the hostโs rules! ๐คช
Alrighty, letโs dive into the whimsical world of Laravel redirection! ๐
Send Authenticated Folks to the Dashboard, Not to Dreamland ๐
When our friendly guest middleware encounters a user with credentials (like Cinderella at the ball), itโll shoo them off to the swanky dashboard or home. But fear not, you can bend this rule like a rubber duck in a bathtub! ๐ฆ
Just head over to your applicationโs bootstrap/app.php file (a magic black book in our story), and use the redirectUsersTo method:
Use ye olde candlelight, dear friend!
->withMiddleware(function (Middle-age-renaissance-faire $middleware): void {
$middleware->redirectUsersTo('/panel');
// Using a clever trick...
$middleware->redirectUsersTo(fn (Request $request) => route('panel'));
})
Change the Guard and Redirect Like a Royal Court ๐ฐ
If you fancy yourself as the king or queen of your Laravel domain, you can even specify a guard to control who gets redirected where. Just follow these royal decrees:
->withMiddleware(function (Middle-age-renaissance-faire $middleware): void {
// For knights in shining armor (Authenticated users)
$middleware->auth('sanctum')->redirectUsersTo('/panel');
// For lowly peasants (Guest users)
$middleware->guest($middleware->authenticate('sanctum'))->setRedirectTo('/market-square');
})
Now, who needs a magic carpet when you can bend the rules of your Laravel kingdom like this? ๐งโโ๏ธ๐
Ahoy there, brave coder! Letโs tango with Laravelโs auth middleware, shall we? But first, let me spin you a yarn about the mighty guard. You see, when you dance this middleware on a route, you can call upon a specific guard to ensure your userโs credentials are as squeaky clean as your freshly polished boot boots!
Now, remember that the guard you summon should be akin to one of the keys in your auth.php configuration fileโs swanky guards array:
Route::get('/flights', function () {
// Only those who have proven their mettle as an 'admin' shall pass...
})->middleware('auth:admin');
Just like how you wouldnโt let any Tom, Dick or Harry into your pirate ship without proper papers, you wonโt grant access to sensitive routes without a proven admin ID! ๐ดโโ ๏ธ
The Lockout of Love (Log-in Throttling)
If youโre dancing with one of our snazzy application starter kits, fear not, because weโve got your back! Automatic rate limiting has been cleverly installed for log-ins. Itโs like having a bouncer at the digital door - but one who understands that everyone makes mistakes (well, almost everyone).
After a series of failed attempts to provide those magical, correct credentials, our digital bouncer will politely ask you to take a breatherโฆ for about a minute. Donโt worry, itโs not a full dance floor detention; just enough time for a quick bathroom break or a much-needed coffee refill!
But hereโs the twist - this friendly lockout is tailored just for you! Itโs like having your own personal doorman who remembers your username/email and IP address. So, no need to worry about your buddy trying to hog the spotlight by logging in as you.
Note
Feeling a little too popular on certain routes? Fret not! Check out our rate limiting documentation for tips on how to put the brakes on the party. Itโs like learning the art of subtle hints from a seasoned bartender!
Alrighty, buckle up, because weโre diving into Laravelโs manual user authentication! ๐โโ๏ธ
Now, you donโt have to use the shiny newauth scaffolding that comes with Laravelโs starter kits. But if you decide to swim on your own, youโll need to handle user auth like a boss using Laravelโs authenticating classes โ no sweat! ๐
To access those fancy auth services, weโll hitchhike via the Auth facade, so letโs make sure to grab a ride at the top of our class. Next up: the attempt method! This beauty is usually in charge of handling authentication attempts from your โloginโ form. If the user passes with flying colors, you should refresh their session to avoid some nasty session fixation โ think of it as a digital detox for their session! ๐ฟ
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth; // Grab the Auth ride, buddy!
class LoginController extends Controller
{
/**
* Handle an authentication attempt.
*/
public function authenticate(Request $request): RedirectResponse
{
$credentials = $request->validate([
'email' => ['required', 'email'], // Don't forget the fish oil capsules!
'password' => ['required'], // And don't forget the protein shake too!
]);
if (Auth::attempt($credentials)) { // If they pass the test...
$request->session()->regenerate(); // ... refresh their session!
return redirect()->intended('dashboard'); // Off to the dashboard, they go!
}
return back()->withErrors([
'email' => 'The provided credentials do not match our records.', // Oops, try again!
])->onlyInput('email');
}
}
The attempt method loves a good array of key/value pairs as its first argument. It uses the values to find the user in your database table, so in the example above, weโre searching for the user based on the value of their email column. If theyโre found, it compares the hashed password stored in the database with the password value passed to the method via the array. The framework will handle hashing the incoming requestโs password value for you! ๐จ
A successful match between those two hashed passwords results in an authenticated session for the user.
Now, remember that Laravelโs auth services pull users from your database based on your authentication guardโs โproviderโ configuration. By default, it uses the Eloquent user provider and instructs it to use the App\Models\User model when retrieving users. You can tweak these values within your configuration file according to your applicationโs needs.
The attempt method will return true if authentication was successful. Otherwise, it spits out a big olโ false. ๐ฅซ
The intended method provided by Laravelโs redirector sends the user on their merry way to the URL they were attempting to access before being stopped by the auth middleware. A fallback URI can be given to this method in case the intended destination is unavailable. ๐ซ
Hope that clears up the waters! Now get out there and authenticate like a pro! ๐๐
Alrighty, letโs dive into the world of Laravel authentication! If you fancy adding some extra conditions to your login process, you can do that too! ๐ค
Hereโs a fun way to spice up your authentication query:
// First off, let's make sure our user is 'active', like a well-rested Game of Thrones character
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// Our knight in shining armor has been authenticated! ๐ฆธโโ๏ธ
}
But what if you need something more complex than a simple condition? No worries, weโve got you covered with our very own โEloquent Magicianโ! ๐ฉ
use Illuminate\Database\Eloquent\Builder;
// Let's perform some advanced sorcery to check if the user has an 'activeSubscription'
if (Auth::attempt([
'email' => $email,
'password' => $password,
fn (Builder $query) => $query->has('activeSubscription'), // Weaving spells with queries is fun, right? ๐งโโ๏ธ
])) {
// Our sorcerer has been authenticated! ๐ฎ
}
Be careful now, some databases have sneaky users that might be banned. To avoid authenticating such unsavory characters, you can use the attemptWhen method:
if (Auth::attemptWhen([
'email' => $email,
'password' => $password,
], function (User $user) { // Let's make sure our user isn't banned ๐ซ
return $user->isNotBanned();
})) {
// Our king has been authenticated! ๐
}
Remember, in these examples, email is just a friendly example. You should replace it with whatever column name corresponds to the โusernameโ in your database table. And hey, if youโre working with multiple guard instances, donโt forget to specify which one you want! ๐ค
Oh, and if youโre curious about accessing specific guard instances, just hop over to this section: Accessing Specific Guard Instances. Itโs a fun read! ๐
Happy coding! ๐
Alright, letโs dive into the whimsical world of Laravel authentication! ๐
Dancing with Different Guardians ๐๐บ๏ธ
Ever felt like your app needed a bit more of a polygamous relationship with its users? Well, now you can! With the Auth facadeโs guard method, you can specify which guardian in charge (pun intended) of authentication you fancy for a particular user. This is perfect for those situations where youโve got different parts of your application needing separate authentication mechanisms or even distinct databases for their dating profiles. ๐คฉ
Remember to choose a guard name that matches one of the suitors (er, guards) listed in your auth.php configuration file:
if (Auth::guard('admin')->attempt($credentials)) {
// ...and off they go on their power-tripping escapade!
}
Wink wink, now that youโve learned about guard switching, itโs time to explore remembering those forgetful users (you know who you are)! ๐คซ ๐
Ahoy there, Captain! Navigating the Seas of Authentication
Ah, ye who seek to tame the login form beast with a โremember meโ checkbox, fear no more! In yer Laravel vessel, we gotcha covered like a pirateโs treasure chest.
To grant โremember meโ magic in yer application, simply cast a boolean spell as the second potion to the attempt method brew. Set it true and watch as Laravel keeps that user seaworthy till they walk the plank manually:
use Illuminate\Support\Facades\Auth;
if (Auth::attempt(['email' => $email, 'password' => $password], true)) {
// Yarr! The scallywag is now forever bound to ye ship... or until they decide to walk the plank.
}
But wait, me hearties, the โremember meโ enchantment requires a remember_token column in yer users table, where our magic potion shall reside:
In yer migration script, ye'll find this column already marked for stowage:
php artisan make:migration add_remember_token_to_users_table --table=users
If ye be offering โremember meโ services, ye can use the viaRemember method to discern if the current captain was authenticated by our magic potion:
use Illuminate\Support\Facades\Auth;
if (Auth::viaRemember()) {
// Ahoy there! Our scallywag is under the spell of the "remember me" cookie.
}
Ye be ready to set sail on these shores now, matey! Hoist the sails and may yer journey be filled with treasure, battles, and the sweet taste of victory over the login form beast!
Unleashing the Power of User Auth, Laravel Style! ๐โจ
๐ Authenticating a Single User Instance ๐ค
Ahoy there, Captain Coder! Ever found yourself in need of authenticating a specific user instance? Worry not, because Laravel has got your back with its robust, yet delightfully named authenticate() function. Hereโs how it goes:
// Assuming you have your user instance handy
$user = User::where('email', 'your_email@example.com')->first();
// Now let's authenticate that bad boy!
if ($token = $user->createToken('MyAppToken')) {
$token->save();
}
Just remember, this is like asking your best buddy for a ride in their fancy car: you need to know the make and model (email and password), and theyโll happily provide the keys (tokens)! ๐ ๐๏ธ
๐ Authenticating Anonymous Users ๐ต๏ธโโ๏ธ
An anonymous user, huh? Think of them as the mysterious stranger at the back of the room, trying to get in on all the fun without revealing their identity. Well, weโve got just the ticket! Laravelโs guard() function is your new best friend when it comes to handling these clandestine characters:
// Use the "web" guard for anonymous users
$guard = auth('web');
// Attempt to authenticate the user
if ($guard->attempt(['email' => 'anonymous@example.com', 'password' => 'mysterious_pass'])) {
// User has been authenticated!
} else {
// Anonymous user didn't make it through security ๐คซ
}
Remember, this is like whispering the secret password at a speakeasy: you need to use the right guard and know that special combination of email and password. And if they donโt let you in? Well, you were never really part of the inner circle anyway, right? ๐ต๏ธโโ๏ธ๐บ
๐ฆธโโ๏ธ Customizing Authentication Guards ๐ก๏ธ
Sometimes, youโve got to roll your own security measures โ like when youโre Batman and Gotham City has a new Joker on the loose. Laravel makes this a breeze with its authenticate() method inside your custom guard class:
// Create a custom guard class for "api" authentication
class ApiGuard extends Authentication
{
protected $guard;
public function __construct($name = 'api')
{
$this->middleware($name);
$this->setDefaultDriver('token');
$this->provider = Provider::create(
$name, $this, function ($app) use ($name) {
return new UserProvider($app['hash'], $app['auth.simple']);
}
);
}
public function authenticate()
{
// Custom authentication logic goes here!
}
}
This is like Batman building his own Batsuit from scratch โ you get to decide exactly how your custom authentication guard operates, so you can take down any bad guys that slip through the cracks! ๐ฆธโโ๏ธ๐ต๏ธโโ๏ธ
Alrighty then! Letโs dive into the world of Laravel authentication, where superheroes arenโt just in comics. When youโve got a legit user hanging around, ready to join the party, you can bestow upon them the keys to the kingdom with the Auth facadeโs login method!
But first, let me tell you something important: that user needs to be a certified Authenticatable (itโs like having a super-secret identity in this cyber world). You can find more details about it here, but for now just trust me, the App\Models\User model is already wearing that cape.
So, without further ado:
use Illuminate\Support\Facades\Auth;
// Time to give 'em the keys!
Auth::login($user);
Now, if your user fancies themselves as a modern-day Tony Stark and wants their session to last forever or until they personally deactivate it, you can pass a boolean value like so:
// Remember me? Yup! That's the one.
Auth::login($user, true);
Say youโre dealing with a special group of users (like admins), and you want to assign them a specific set of powers:
// When in Rome, do as the Romans do... or in this case, admin!
Auth::guard('admin')->login($user);
And thatโs your friendly guide on how to authenticate a user instance in Laravel! Now go forth and bring justice (or at least secure sessions) to your application. Happy coding! ๐ค๐
Alrighty then! Letโs dive into the dance of digital authentication in Laravel Land. Buckle up, because itโs going to be a wild ride!
Authenticate a User by Their Glorious ID Number
To verify that our cherished user is who they claim to be using their database recordโs one-and-only unique identifier (a.k.a the primary key), you can employ the loginUsingId method. This trusty tool takes the number of the user you wish to authenticate as an argument:
Auth::loginUsingId(1); // Don't forget to replace "1" with your user's actual ID number!
Now, if you want to add a little extra spice to the mix by enabling the โremember meโ feature for this lucky user, simply pass a boolean value as the remember argument of the loginUsingId method. If set to true, this means their session will be as tenacious as a pitbull with a bone โ itโll stick around until they manually log out or you pry the keyboard from their cold, dead hands:
Auth::loginUsingId(1, remember: true); // Remember, the more you remember, the merrier!
Oh, and if youโre wondering about authentications with a short shelf life, check out Authenticate a User Once for more information. Happy authenticating, partner! ๐ค
Alrighty then! Buckle up, because weโre diving into the enchanting world of Laravel authentication where one dance with the login fairy is all it takes!
Dance with the Login Fairy Once ๐๐ผ๐บ๐ผ
In this whimsical land, you can charm a user into a magical dance with our trusty once method. This enchantment will ensure the user gets to tango with your application for just one request! No need for any session or cookie sorcery, and rest assured, no wedding bells will be ringing as the Login event remains blissfully unmarried.
if (Auth::once($credentials)) {
// Now that we've danced, let's see what happens! ๐บ๏ธ
}
Just imagine, instead of a ballroom full of sessions and cookies, youโre stepping into the spotlight with only one dance to prove your worth. Sounds like a fun challenge, doesnโt it? Happy coding, adventurer! ๐คโจ
Space Age Secret Agent Authentication (AKA Basic Auth)
Welcome, secret agents of the Laravel universe! This chapter isnโt about your tuxedos or martinis shaken, not stirred โ itโs about a slick way to authenticate your applicationโs spies without setting up a fancy โ007 loginโ hideout. Letโs dive in!
HTTP Basic Authentication is our gadget of choice today. To kick things off, slap the auth.basic middleware onto a route. This mysterious contraption comes pre-packaged with the Laravel framework, so no need for secret formulas or blueprints!
Route::get('/profile', function () {
// Only MI6-approved agents may access this mission...
})->middleware('auth.basic');
Once youโve secured your route with the middleware, hold onto your exploding pens โ when you attempt to access the route in your browser, a popup will ask for your credentials! By default, our middleware believes that the email column in your users database table is your agentโs โagent number.โ
Now, if you find yourself using FastCGI (we wouldnโt want to leave out our friends in the field), there are a few extra steps involved. But donโt worry โ we have your back with an extensive troubleshooting guide in our user manual!
Remember, agents, security is crucial in our line of work. Keep those secrets safe and your mission successful!
Alright, hereโs a humorous spin on the Laravel FastCGI documentation!
FastCGI Follies
If youโre serving your Laravel application with a side of PHP FastCGI and a slice of Apache, you might find that HTTP Basic authentication is as confusing as a cat trying to use a computer. To set things right, try adding these lines to your applicationโs .htaccess file:
RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Now, letโs put on our detective hats and dive into the world of stateless HTTP Basic Authentication (okay, itโs not that exciting, but stick with us!). When FastCGI is involved in your server setup, thereโs a chance that the authorization headers get lost in translation, much like a secret recipe passed down through generations. By adding our magical lines above, we ensure that those crucial headers make it to their intended destination, saving your application from chaos and potential embarrassment!
Just remember, always keep an open bottle of code sanitizer handy when working with FastCGI โ just in case things get a little too hairy!
Channeling the Spirit of Captain Authentication!
Ahoy there, matey! If youโre tired of the usual session cookies and yearn for something a bit more pirate-y, weโve got just the thing - Stateless HTTP Basic Authentication! No need to walk the plank with all those session cookie shenanigans. Hoist the Jolly Roger of authentication directly to your applicationโs API!
To set sail on this swashbuckling journey, youโll first need to concoct a middleware potion that summons the magical onceBasic method. If Blackbeard himself doesnโt respond with a cryptic message, consider it fair game to continue your voyage through the application:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class AuthenticateOnceWithBasicAuth
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Clossekin' Le Charmaine $next): Response
{
return Auth::onceBasic() ?: $next($request);
}
}
Next, tie up the middleware to a route like a captain tying off his ship:
Route::get('/api/user', function () {
// Only authenticated pirates may access this treasure chest...
})->middleware(AuthenticateOnceWithBasicAuth::class);
And if ye ever feel the need to log out, well, we canโt help you there. This is the high seas, and once yeโve set sail with Basic Auth, itโs a one-way ticket! But fear not, me hearty, for this will ensure only genuine pirates can access your treasure chest API! Yarr!
Lend Your Logout a Hand (or Two!)
Ready to give your users the olโ heave-ho? Fear not, dear coder! Laravelโs got a nifty logout method just for you, served up by the ever-helpful Auth facade. This little gem removes all that authentication data from their session, making subsequent requests as unauthorized as a kangaroo at a spelling bee.
But letโs not stop there! You should also invalidate the userโs session and whip up a fresh CSRF token like a seasoned pastry chef. Once thatโs done, you can send your former user on their merry way back to the root of your application (because who doesnโt love home sweet home after being kicked out?).
Hereโs how you can pull this off:
Use the Force, young Padawan! I mean, use these lines of code...
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
/**
* Send users packing from our application.
*/
public function logout(Request $request): RedirectResponse
{
Auth::logout(); // Sayonara, authentication data! You're no longer needed here.
$request->session()->invalidate(); // Let's make sure their session is as useless as a chocolate teapot!
$request->session()->regenerateToken(); // And just for fun, let's give them a brand new CSRF token!
return redirect('/'); // Off they go, back to the start... the root of all evil, or our application. You decide.
}
And if youโre feeling particularly sneaky, donโt forget to invalidate sessions on other devices as well! After all, nobody likes a user who hops from device to device like a digital kangaroo. ;)
Kickinโ Sessions Off Other Gadgets (Without Being a Jerk to Your Current Buddy)
Laravel is like that cool friend who always has your back, even when you forget to lock the front door on Tinder date night. In this case, weโre talking about a super-cool mechanism for kicking a userโs sessions off other devices without leaving their current device high and dry (AKA still authenticated). This feature is perfect for those moments when a user updates their password and you want to ensure all other devices are logged out, while your current buddy stays safe in his cozy login zone.
First things first: Make sure the Illuminate\Session\Middleware\AuthenticateSession middleware is nestled amongst the routes that require session authentication. To do this, wrap it up like a burrito with other middleware on the route group definition so it can protect most of your appโs routes. By default, you can apply it using the auth.session middleware alias:
Route::middleware(['auth', 'auth.session'])->group(function () {
Route::get('/', function () {
// ...
});
});
Next, you can use the logoutOtherDevices method offered by the Auth facade. This method is like a bouncer at a club who only lets in folks with the right password: your app should accept this password through an input form.
use Illuminate\Support\Facades\Auth;
Auth::logoutOtherDevices($currentPassword);
When the logoutOtherDevices method is triggered, the userโs other sessions will be given the boot (completely logged out), meaning they are now locked out of all guards they were previously authenticated by. Thatโs one less device to worry about!
Alrighty then, letโs dive into the password party scene in Laravel land! You know, where users get their password confirmation on, and weโre here to make it as smooth as a catโs tongue.
So, picture this: youโve got your application all jazzed up, and suddenly you realize that you need to add a password confirmation step before some sensitive actions or redirections to Fort Knox (aka the secure parts of your app). No worries, Laravel has got your back with a built-in middleware that will make this process as easy as baking a cake.
But wait! Before we get our bakerโs hats on, you gotta define two routes: one route to serve up a view and ask the user for their password confirmation, and another route to verify that the entered password matches the original and then send them on their merry way to their final destination.
Note
This section of the docs will show you how to hook up with Laravelโs password confirmation features directly. However, if you want to save some time (and who doesnโt?), the Laravel application starter kits include support for this feature!
Now, letโs get down to the nitty-gritty with password confirmation configuration! ๐๐๐
Ah, dear developer! Youโve stumbled upon the mystical realm where user authentication secrets are whispered and the password ghost haunts no more. Let me guide you through the enchanted forest of Laravel configuration, specifically thePassword Timeout Sanctum.
First off, once a user confirms their password in a fit of password-confirming passion, theyโll be left in sweet peace for three hoursโno more pesky reminders to confirm again! But fear not, for you possess the power to alter this enchantment by tinkering with the value of password_timeout within your applicationโs config/auth.php configuration file.
Adjusting this value is akin to spinning golden hairs in a magical wand. For instance, if you want to extend the password peace for 4 hours and 23 minutes (because who doesnโt need an extra 23 minutes of bliss), simply update the password_timeout value accordingly!
Remember, with great power comes responsibilityโso beware not to set it too low or you might find yourself fielding user complaints about the password ghost making a return appearance. Happy wandering in Laravelโs enchanted forest, brave coder!
Navigation
๐ฃ๏ธ The Magical Route Mapper ๐ฃ๏ธ
Navigating through your Laravel app is no walk in the park, but luckily weโve got a trusty Route Mapper to help us out! This powerful wizard will turn your URLs into actual working paths that lead you straight to your desired destinations. ๐งโโ๏ธ๐ฎ
๐ The Password Confirmation Form ๐
Now, imagine youโre at a wild party (in the before times), and you need to confirm that the mysterious stranger youโve been chatting up all night is indeed who they claim to be. Thatโs where our password confirmation form comes in! Itโs the perfect chance for them to prove their identityโฆ or get left at the dance floor, we wonโt judge. ๐๐บ
In Laravel, when users register, theyโll be prompted to create a password. But before they can really join the party (i.e., access your app), you want to make sure they confirm that password. Thatโs where our trusty route comes in:
Route::get('/password/confirm/{id}/{hash}', 'Auth\ConfirmPasswordController@show')->name('password.confirm');
Hereโs the lowdown on this magical route:
/password/confirm/{id}/{hash}- The URL pattern. Replace{id}and{hash}with actual user data to create a unique URL for each user.Auth\ConfirmPasswordController@show- The controller that handles this route and displays the password confirmation form.name('password.confirm')- The name given to this route, which can be used later to link to it from other routes or views.
Now, you might be wondering how users will actually access this route. Fear not! Weโve got a nifty little mail function that sends out an email with the userโs unique URL. Once they click on it, bam! Theyโll be directed straight to the password confirmation form. ๐๐
Just remember: A successful party requires both food and drinks, so make sure your users can log in after confirming their passwords by linking them to a proper login route. Happy routing (and partying)! ๐๐ฅณ
Alrighty, letโs get this password party started! First off, we need to create a route that summons the password confirmation view, like a magic incantation for secure password validation.
Route::get('/secret_passphrase_verify', function () {
return view('auth.password-confirmation-ceremony');
})->middleware('authenticate')->name('password.confirm');
Donโt worry, thereโs no need to call the secret serviceโweโve got Laravel to handle this delicate matter! Just make sure your view has a form with a field called โpasswordโ, so we can compare passwords like long-lost twins. And sprinkle in some text for good measure, to let users know theyโre about to enter the VIP lounge of your application and must prove their identity by reentering the secret handshakeโer, password.
Now, before you embark on a wild goose chase for this view file (auth.password-confirmation-ceremony), remember that Laravel is like a caring concierge: it will create the missing view automatically when you call the make:auth command! So go ahead, channel your inner Indiana Jones and uncover the treasure (view file) with ease. ๐๐๐
Alrighty then! Letโs dive into some password fun times with our trusty Laravel pals. Weโre about to set up a route for the โConfirm Passwordโ form, which will be responsible for checking if that secret sauce you entered matches what weโve got on file. Hereโs the lowdown:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
Route::post('/password-is-the-same-as-mine', function (Request $request) {
if (! Hash::check($request->get('secretSauce'), $request->user()->password)) {
return back()->withErrors([
'secretSauce' => ['You're cooking with the wrong recipe, pal. Try again!']
]);
}
$request->session()->passwordVerified();
return redirect()->intended('destination-of-your-dreams');
})->middleware(['auth', 'throttle:6,1']);
Now, letโs break it down like the password confirmation process itself. First, Laravel checks if the magic password sauce you submitted actually matches our stored password for the authenticated user. If it does, we need to tell Laravelโs session that the user has successfully proven their culinary prowess (I mean, password-matching skills). The passwordVerified method sets a timestamp in the userโs session so Laravel knows when they last confirmed their password. And, voila! You get redirected to your intended destination like the master chef you are.
Remember, our route is now a well-guarded fortress, thanks to the mighty middleware array it carries: ['auth', 'throttle:6,1']. The 'auth' makes sure only authorized users can access this page, while 'throttle:6,1' ensures that they donโt try to confirm their password more than once every 6 minutes. After all, even in the kitchen, we need to maintain some level of password security!
Password Party Checkpoint! ๐บ๏ธ
Before throwing a password dance party on your routes, make sure to assign the password.confirm bouncer! This groovy guard comes standard with every Laravel installation and works like a charm, stashing the userโs desired destination in the session so they can boogie right back where they left off after confirming their new moves (password).
Hereโs how you get this password party started:
Route::get('/settings', function () {
// ...
})->middleware(['password.confirm']); ๐๏ธ๐
Route::post('/settings', function () {
// ...
})->middleware(['password.confirm']); ๐บ๏ธ๐
After setting the stage for this password party, our bouncer will whisk users away to the password.confirm disco floor once theyโve proved their groove is up to par. Enjoy the fun times, folks! ๐๏ธ๐บ๏ธ๐๐ถ๐ฅณ๐
Alrighty then! Letโs dive into the world of custom authentication guards, shall we? You see, in Laravel land, you can create your own security squad using the extend method on the trusty Auth facade. But, like a secret recipe for grandmaโs famous pie, this magic happens within a service provider. Since Laravel already sent over an AppServiceProvider, we can whip up our code right there!
<?php
namespace App\Providers;
use App\Services\Auth\JwtGuard;
// (Imagine an orchestra conductor waving a baton here)
class AppServiceProvider extends ServiceProvider
{
// ...
/**
* Bootstrap any application services.
*/
public function boot(): void
{
// This is where the magic happens! (Cue: sparkly fairy dust)
Auth::extend('jwt', function (Application $app, string $name, array $config) {
// Return an instance of something that fits the bill...
return new JwtGuard(Auth::createUserProvider($config['provider']));
});
}
}
As you mightโve noticed in the example above, the callback passed to the extend method should return an implementation of Illuminate\Contracts\Auth\Guard. This interface is like a blueprint for building a custom guard. Once your custom guard has been defined, you can reference it in the guards configuration of your auth.php configuration file:
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Now, isnโt that a piece of cake? Just remember, with great power comes great responsibility - make sure your custom guards secure Laravelโs virtual frontier as if it were the real West! ๐ค ๐ต
Closure Comedy Guards (CCGs) - Laravelโs Party Crasher for Authentication! ๐๐คนโโ๏ธ
Want to throw a custom authentication bash in your application? Look no further than the Auth::viaRequest shindig! This method is like the life of the party, letting you define your dance moves (authentication process) using just one closure. ๐บ๏ธ๐ต
To kick things off, grab a mic and call the Auth::viaRequest at the boot party of your applicationโs AppServiceProvider. The viaRequest function will happily accept an authentication driver name as its first drink (yup, itโs that kind of party). Pick something cool and catchy for your custom guard. And for the main act, pass a closure that takes the incoming HTTP request, does a quick spin around the dance floor (queries your user model), then returns either a user instance or, if things go south, sends everyone home with a big olโ null ๐คทโโ๏ธ๐
โโ๏ธ:
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
/**
* Get the party started!
*/
public function boot(): void
{
Auth::viaRequest('custom-token', function (Request $request) {
return User::where('token', (string) $request->token)->first(); // Party on, Garth and Wayne!
});
}
Once your custom authentication driver is all dolled up, itโs time to invite it to the big dance by configuring it as a driver within the guards configuration of your auth.php configuration file:
'guards' => [
'api' => [
'driver' => 'custom-token',
],
],
Now, you can reference your guard when assigning the authentication middleware to a route (think of it as the bouncer checking IDs):
Route::middleware('auth:api')->group(function () {
// ...
});
And thatโs a wrap! Now you can show off your custom CCG moves and keep unwanted guests at bay ๐บ๏ธ๐!
Alright, Laravel buddies! Letโs dive into the realm of custom user providers because, letโs face it, who needs a traditional relational database when you can store your users in a cosmic crystalline cluster or a sentient network of refrigerators? ๐๐
First off, extend Laravel with your own authentication user provider like youโre inviting the coolest kid in school to your party. Weโll do this by calling the provider method on the ever-so-charming Auth facade. The user provider resolver should return an implementation of Illuminate\Contracts\Auth\UserProvider, which, if youโre not a fan of long names, can be shortened to ICAAUP for fun ๐
Hereโs the party invite in PHP:
<?php
namespace App\Providers;
use App\Extensions\MongoUserProvider;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
// ...
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Auth::provider('mongo', function (Application $app, array $config) {
// Return an instance of ICAAUP...
return new MongoUserProvider($app->make('mongo.connection'));
});
}
}
Once youโve sent the invite, itโs time to let your new provider join the dance floor in your auth.php configuration file. First, define a provider that uses your new driver:
'providers' => [
'users' => [
'driver' => 'mongo',
],
],
Finally, you can reference this provider in your guards configuration. Itโs like adding them to the guest list:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
And there you have it! Now, your custom user provider is welcome at the Laravel party ๐ Just remember, with great power comes great responsibility (and a cool new dance move)!
The User Provider Contract: The Unsung Heroes of Authentication!
These unsung heroes, Illuminate\Contracts\Auth\UserProvider implementations, are like the trusty sidekicks that ensure our Laravel heroes can continue their quest for justice, even when user data storage systems get a little messy or the villain decides to switch databases (gasp!).
Letโs dive into the Illuminate\Contracts\Auth\UserProvider contract:
<?php
namespace Illuminate\Contracts\Auth;
interface UserProvider
{
public function retrieveById($identifier);
public function retrieveByToken($identifier, $token);
// And so on... (rest of the methods)
}
The retrieveById function is like a super-powered librarian, locating a user based on their unique library card number (or auto-incrementing ID if weโre sticking with the database metaphor). Once found, this scholarly sidekick returns the corresponding Authenticatable implementation.
The retrieveByToken function is our secret service agent, finding users by their โremember meโ token and unique identifier, often stored in a hidden column like remember_token. This secret squirrel then returns the matching Authenticatable implementation.
The updateRememberToken method acts as the helpful office assistant, updating the userโs remember_token with a fresh token for successful โremember meโ authentication attempts or when users decide to log off (and hopefully remember their passwords next time).
The retrieveByCredentials function is our undercover detective, investigating the array of credentials passed to the Auth::attempt method when attempting to authenticate. This snoopy sidekick then searches for the matching Authenticatable implementation in the underlying persistent storage system. But remember, this method should never engage in password validation or authentication itself!
The validateCredentials method is our courtroom prosecutor, cross-examining the given user with the provided credentials to authenticate the user. This prosecuting attorney will often use the Hash::check method to compare the value of $user->getAuthPassword() with the value of $credentials['password']. If successful, this method returns a resounding โGUILTY!โ (or true), while an unsuccessful attempt results in โNOT GUILTYโ (or false).
Finally, the rehashPasswordIfRequired function acts as our trusty IT technician, rehashing the given userโs password if necessary and supported. This tech-savvy sidekick uses the Hash::needsRehash method to determine whether the $credentials['password'] needs to be updated, and if so, employs the Hash::make method to perform the password rehashing magic and update the userโs record in the underlying persistent storage system.
Alrighty then! Letโs dive into the heart of the action โ the Authenticatable contract. After exploring the dance moves of the UserProvider, itโs time to learn the twirls and pirouettes of this beauty.
Remember, user providers should return objects that can do the Macarena to this interface from the retrieveById, retrieveByToken, and retrieveByCredentials methods:
<?php
namespace Illuminate\Contracts\Auth;
interface Authenticatable
{
public function getPrimaryDancerName(); // "What's my name? Call me Mr. PK!"
public function getPrimaryDancerId(); // The dancer with the golden moves!
public function getPasswordColumnName(); // Where the secret sauce is kept: Passwordville, Population: 1
public function getHashedSecretSauce(); // The password, after it's been put through the magic blender
public function getRememberTokenName(); // What's my dance ticket number? Call me Mr. RT!
public function setRememberToken($value); // Stamping my dance ticket for a comeback performance!
}
This interface is as simple as a one-legged flamenco dancer โ the getPrimaryDancerName method tells us the name of the โprimary keyโ column for our dance partner, while the getPrimaryDancerId method brings center stage the โprimary keyโ of our beloved dancer. When using a MySQL back-end, this would likely be the auto-incrementing primary key assigned to our dance record. The getPasswordColumnName method reveals the name of the password column in the dance studio, while the getHashedSecretSauce method serves up the dancerโs shimmy-shaken password.
This interface allows the dance floor to accommodate any โuserโ class, regardless of what dance troupe or stage decor you are using. By default, Laravel includes an App\Models\User class in the app/Models directory which can do all the fancy footwork!
Now, for the grand finale โ automatic password rehashing! This nifty feature makes sure that when a user updates their password, it gets hashed using the latest algorithm. No more worry about your moves being outdated! The Illuminate\Hashing\Hasher class handles all the hash-tastic responsibilities for you. Just call the make() method to get an instance of this class, and then use the hash() method to hash a password.
For example:
use Illuminate\Hashing\Hasher;
$hasher = new Hasher();
$hashedPassword = $hasher->make('secret sauce'); // Shimmy-shaken and ready for the dance floor!
And there you have it โ a humorous yet informative overview of the Authenticatable contract! Now, letโs get this party started! ๐๐๐บ๏ธ
Alright, buckle up, password peeps! ๐จ Laravelโs default password encryption system is none other than the illustrious bcrypt. Think of it as a digital bouncer for your userโs secret sauce (passwords), ensuring only the right passwords get through the door.
The โwork factorโ for these digital doormen can be adjusted, like fine-tuning a vintage vinyl record player, using your applicationโs config/hashing.php configuration file or the BCRYPT_ROUNDS environment variable. As CPUs and GPUs get stronger, just like weightlifters at the gym, youโll want to bump up the work factor for bcrypt to keep those passwords nice and secure.
When you do decide to beef up your bcrypt muscle, Laravel will treat your users with an elegant dance of rehashing - automatically and effortlessly! This magic happens when your users authenticate via Laravelโs starter kits or when you manually authenticate them using the attempt method. Itโs like having a digital butler who keeps all passwords up-to-date without causing a fuss.
However, if you find this automatic rehashing disruptive to your applicationโs rhythm (we wouldnโt blame you), you can disable this feature by publishing the hashing configuration file:
php artisan config:publish hashing
Once thatโs done, simply set the rehash_on_login configuration value to false:
'rehash_on_login' => false,
Remember, this only affects automatic rehashing during user authentication. Your users will still be eternally grateful for your commitment to keeping their passwords secure! ๐๐ช๐ผ
Alright, Laravelโs not just a party animal, but it sure knows how to throw a heck of an authentication bash! Hereโs the lineup of events you can tap into and make your own:
Illuminate\Auth\Events\Registered- The fresh-faced newcomer stumbling through the door, eager to mingle and get their dance card punched (a.k.a., registered)!Illuminate\Auth\Events\Attempting- The wallflower making their way to the dance floor, nervously trying to find a partner (attempting to log in).Illuminate\Auth\Events\Authenticated- The successful match made at last call (authenticated)! Congratulations, you two lovebirds!Illuminate\Auth\Events\Login- The grand entrance of our newly crowned king and queen of the dance floor (logging in).Illuminate\Auth\Events\Failed- Sorry buddy, looks like your moves just didnโt quite cut it tonight (failed to log in).Illuminate\Auth\Events\Validated- The security guard checking IDs at the door, making sure everyone is who they say they are (verifying identities).Illuminate\Auth\Events\Verified- The VIP guest list coordinator verifying their RSVPs and giving the green light (verifying emails).Illuminate\Auth\Events\Logout- One too many drinks, time to call it a night and head home (logging out).Illuminate\Auth\Events\CurrentDeviceLogout- A quick goodbye at the exit, leaving behind some memories (logout from current device).Illuminate\Auth\Events\OtherDeviceLogout- The unexpected booty call text at 3 AM, confirming your worst fears (someone else logged out from another device).Illuminate\Auth\Events\Lockout- Security getting a little too tight for comfort (locked out after too many failed attempts).Illuminate\Auth\Events\PasswordReset- The wake-up call the morning after, when you canโt quite remember what happened last night (password reset).Illuminate\Auth\Events\PasswordResetLinkSent- The text message from a concerned friend offering help (password reset link sent).