Passport or Sanctum? ๐ค๐ค๐ค
Oh, the choices! Are you a wizard seeking enchanting access control for your API? Or do you prefer the sleek and powerful Sanctum? Either way, weโve got your back!
Deploying Passport ๐๐ฐ
Welcome to the realm of Passport! To get started, just follow these simple incantationsโฆ errrโฆ instructions.
Upgrading Passport ๐๐
Level up your API security by upgrading Passport! Itโs like getting a superpower upgrade for your magical artifact! ๐ โจ
Token Lifetimes โฒ๏ธ๐พ
Customize the lifespan of your magic tokens. From short-lived potions to everlasting elixirs, itโs all up to you!
Overriding Default Models ๐๐ฆ
Swap out our default models for your very own magical creatures! Itโs like choosing your Hogwarts house all over again.
Overriding Routes ๐๐งโโ๏ธ
Design your own secret pathways through the labyrinth of APIs! Just make sure to leave breadcrumbs for others, wonโt you? ๐
Authorization Code Grant ๐๏ธ๐
Unlock the power of access control through the ancient ritual of Authorization Code Grant! Master this art and rule your kingdom with wisdom and grace.
Managing Clients ๐ฅ๐บโโ๏ธ
Welcome new clients to your API realm, ensuring theyโre well-versed in your magic spells.
Requesting Tokens ๐๐ฌ
Connect with clients using the enchanted Phone of Token Request! Itโs like making a magical house call ๐กโจ
Managing Tokens ๐ต๏ธโโ๏ธ๐๏ธ
Keep tabs on your magic tokens, their origins, and their secrets. Itโs like being a spy in the court of fairy tales!
Refreshing Tokens ๐ฑโ๏ธ
Rejuvenate your magic tokens before they lose their power! Like replenishing a wand with dragon heartstring.
Revoking Tokens โ๏ธ๐คฌ
Dispel unwanted magic tokens and banish them from your API realm forever!
Purging Tokens ๐ฅ๐๏ธ
Sweep away old, stale tokens and start fresh with new ones! Itโs like spring cleaning for your magical API kingdom.
Authorization Code Grant With PKCE ๐ก๏ธ๐
Add an extra layer of security to the Authorization Code Grant with Proof Key for Code Exchange (PKCE)! Itโs like donning a magical amulet that makes your spells harder to counterfeit.
Device Authorization Grant ๐ฑโ๏ธ
Let trusted devices access your API with the Device Authorization Grant! Itโs like granting them a magical key to the castle.
Password Grant ๐๏ธ๐ค
Grant clients direct access to your API using the ancient Password Grant! Just make sure they keep their magic passwords safe and secret!
Customizing the User Provider ๐ ๏ธ๐ฉ
Tinker with the inner workings of your user provider, like a master artificer crafting enchanted objects.
Customizing the Username Field ๐๏ธโโ๏ธ๐ฌ
Change the field name for the username in your API, like switching characters in a TV show!
Customizing the Password Validation ๐ก๏ธ๐ฒ
Tailor the password validation rules to fit the needs of your magical kingdom.
Implicit Grant โ๏ธโจ
Access API resources directly through the Implicit Grant! Itโs like casting a spell without needing a wand.
Client Credentials Grant ๐ก๏ธ๐
Enable your clients to access protected resources using their magic credentials! Itโs like opening a locked door with a magical key.
Personal Access Tokens ๐๐ฆ
Empower yourself or your users with Personal Access Tokens! Theyโre like having your very own dragon that guards the treasure chest of API access.
Creating a Personal Access Client ๐ ๏ธ๐ฒ
Forge your personal access client with fire and magic, just like crafting a legendary sword.
Customizing the User Provider for PAT ๐ฉ๐งช
Customize the user provider settings specifically for Personal Access Tokens, like tailoring a suit of armor to fit perfectly.
Managing Personal Access Tokens ๐๐ฐ
Keep track of your personal access tokens, just like maintaining a library of ancient scrolls.
Protecting Routes ๐ก๏ธ๐ ๏ธ
Secure your API routes using enchantments and powerful middleware! Itโs like creating a magical barrier around your most valuable resources.
Via Middleware ๐งโโ๏ธ๐ต๏ธโโ๏ธ
Enhance your middleware with protective spells, just like forging a magic ring of invisibility.
Passing the Access Token โ๏ธ๐
Share your access token with other magical artifacts in your API kingdom, enabling seamless communication and cooperation.
Token Scopes ๐ฆโจ๐น
Define the boundaries of your magic tokens using scopes! Itโs like creating a map of forbidden forests and safe havens within your API realm.
Defining Scopes ๐๐
Mark off specific areas within your API, allowing or restricting access based on scopes.
Default Scope ๐ฐ๐
Set a default scope for your magic tokens, ensuring that everyone starts with the same level of access.
Assigning Scopes to Tokens โ๏ธ๐งฉ
Bestow scopes upon your magic tokens, like granting a knight their coat of arms.
Checking Scopes ๐ต๏ธโโ๏ธ๐
Validate whether a magic token has certain scopes, acting as a gatekeeper for protected resources.
SPA Authentication ๐๐
Enable Single Page Application (SPA) authentication with ease! Itโs like adding a magical spell to your web development potions.
Events ๐๐
Stay in the loop and respond to important events happening within the Passport realm, like a magical oracle guiding the kingdom.
Testing ๐งช๐ฌ
Perform enchantments and potion experiments on your API with thorough testing! Itโs like having a laboratory to brew the perfect magic elixir.
Hey There, Captain! ๐
Welcome to Laravel Passport - the OAuth2 superpower youโve been waiting for your Laravel app! This bad boy is like Batmanโs utility belt for web development. Itโs so easy to set up, even a penguin could do it (and we all know how clumsy they are with keys!).
Under the hood, Passport is built upon the mighty League OAuth2 server, maintained by the dynamic duo Andy Millington and Simon Hamp. Think of them as your Robin and Batman - always there to lend a helping hand when you need it most.
[!ATTN: BAT-SIGNAL TIME] This documentation assumes youโve already brushed up on your OAuth2 knowledge. If youโre still in Gotham City learning about bats and passwords, be sure to check out the general terminology and features of OAuth2 before we continue our adventure.
Now that we have the formalities out of the way, letโs dive into this superhero suite and make your Laravel app more secure than Fort Knox! ๐ฆธโโ๏ธ๐ช
Passport vs. Sanctum: The Authentication Showdown! ๐ฅ
Before we dive into the fray, letโs figure out which Laravel knight you need for your appโs quest - Passport or Sanctum! If you find yourself in dire need of OAuth2 support, then Passport is your paladin.
On the other hand, if youโre looking to authenticate a valiant single-page adventure, mobile escapade, or simply issue some API tokens, itโs time to summon Laravel Sanctum! Unlike its OAuth2 brethren, Sanctum prefers a more straightforward approach to authentication, making it perfect for your questโs simplified development experience.
Now, let the games begin! ๐ฒ (And yes, we just compared authentication systems to medieval heroes and tabletop games - because who said learning couldnโt be fun?)
Alright, grab your popcorn and buckle up, because weโre about to embark on a wild Laravel Passport adventure! ๐
First off, letโs get this party started with the install:api Artisan command. You can think of it as the magic wand that brings life into your applicationโs OAuth2 clients and access tokens. To summon it, simply chant these mystical words in your terminal:
php artisan install:api --passport
Just like a Jedi master casting a spell, this command publishes the necessary database migrations to create the tables for storing OAuth2 goodness. It also conjures up some encryption keys to ensure those access tokens stay secure and top-secret. ๐
Once youโve run the install:api spell, itโs time to bestow your App\Models\User model with a touch of Passport magic by adding the HasApiTokens trait and the OAuthenticatable interface. Think of it as giving your user model superpowers, enabling it to inspect the authenticated userโs token and scopes. ๐ฆธโโ๏ธ
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\Contracts\OAuthenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable implements OAuthenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
Last but not least, head over to your applicationโs config/auth.php configuration file and define an api authentication guard, setting the driver option to passport. This tells your application to use Passportโs TokenGuard when authenticating incoming API requests. Itโs like telling a bouncer at a secret club: โOnly let in those with Passport tokens!โ ๐คซ
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
And voila! Youโre all set with Laravel Passport, ready to defend your application against unwanted guests and serve authenticated content like a well-oiled API machine. ๐
Alright, buckle up, coding cowboys and codelettes! Itโs time to learn about deploying Laravel Passport, the swiss army knife of authentication. But first, a little joke: Why did the encryption key refuse to play hide and seek with the access token? Because it always hides in plain sight โ and thatโs exactly where we want it!
Now, letโs get down to business. When youโre about to saddle up Passport on your applicationโs servers for the very first time, youโll likely need to rope in the passport:keys command. This command is like a cowboy corraling those encryption keys that Passport needs to lasso access tokens:
php artisan passport:keys
Rest assured, these generated keys usually donโt need to be branded and roped into your source control herd (unless youโre a really curious coyote).
If you find yourself needing to specify the path where Passportโs keys should graze, fear not! You can use the Passport::loadKeysFrom method to wrangle them in. Generally, this method should be called from the boot method of your applicationโs App\Providers\AppServiceProvider class:
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Passport::loadKeysFrom(__DIR__.'/../secrets/oauth');
}
For those of you who prefer to let your environment do the wrangling, you can use Laravelโs key vault system. Itโs like having your own personal cowboy who keeps an eye on your keys (and secrets) and hands them over only when needed! To load Passportโs keys from the environment, simply unleash the Passport::keyFor method:
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Passport::keyFor('oauth_client', function ($key) {
$key->expiresAt(now()->add Years(10));
});
}
And thatโs a wrap, partner! Now you know how to keep those keys safe and sound while lassoing in access tokens like a seasoned cowboy (or cowgirl)!
Alrighty then! Letโs get this pastry party started! ๐ฅง
Baking Your Secrets From the Cookie Jar (I mean, Environment)
Now, if you fancy publishing Passportโs recipe book using the Artisan kitchen aid, hereโs the magic spell:
php artisan bake-off --tag=passport-config-platter
Once your secret ingredients have been whipped up and served on a silver platter (or, you know, published), itโs time to set the table for your applicationโs cryptic cocktails. Just sprinkle some environment variables around like so:
KEY LIME PIE_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
<private key here>
-----END RSA PRIVATE KEY-----"
STRAWBERRY SHORTCAKE_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----
<public key here>
-----END PUBLIC KEY-----"
Remember, kids: always keep your keys and cocktails locked up tight! ๐๐ธ
Passportโs Majorgasmic Upgrade Guide! ๐๐
Prepare for takeoff, dear developer! As you soar through the software stratosphere towards a new major version of Passport, itโs crucial to buckle up and carefully read this guide. Ahemโฆ ahem ๐
The Nitty-Gritty on Configuration ๐ง
Before you dive headfirst into the upgrade, itโs essential to check out our upgrade guideโjust like checking the safety demo before a rollercoaster ride! This handy doc will ensure your Passport setup transitions as smoothly as a well-oiled seagull. ๐ฆ
Now, remember: no one wants a crashed spaceship, so take it slow and steady, and youโll be cruising through the cosmos in no time! Happy upgrading! ๐๐โจ
Ahoy there, brave coder! ๐ค Letโs dive into Laravelโs configuration settings, a veritable treasure trove for those who seek to tame the digital ocean.
First up, we have the token lifetimes! ๐ These arenโt just your everyday time-keeping gadgets; theyโre the guardians of your applicationโs security. You can set them according to your applicationโs needs, ensuring those tokens donโt outlive their usefulness or overstay their welcome.
// Here be the token lifetimes configuration! ๐๐ฒ
// Access tokens live for this many minutes after they've been issued
config(['auth.guards.api' => ['passwords' => [
'lifetime' => env('AUTH_PASSWORDS_LIFETIME_MINUTES', 60),
]]]);
Next, thereโs the database connection configuration. This is akin to mapping out your digital realms, connecting them all together in one grand network.
// Connect ye to the databases! ๐ฐ๐ฒ
// Here's an example of a database connection named 'puff_skeleton'
$connection = [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefixes' => [
// The default table prefix used by Laravel.
// Most applications don't need to modify this value.
'posts' => 'puff_',
],
];
Lastly, the cache configuration. This is where we stash away all the valuable data that doesnโt change too often, making your app run swifter than a cheetah on roller skates.
// Cache away! ๐ฐ๐ฒ
// Here's the cache configuration for using Redis as the cache driver
config(['cache.default' => 'redis']);
config(['cache.stores.redis' => [
// The connection name to use when connecting to Redis.
'connection' => env('CACHE_REDIS_CONNECTION', 'default'),
// The Redis instance host to connect to.
'host' => env('CACHE_REDIS_HOST', '127.0.0.1'),
// The port the Redis instance is listening on.
'port' => env('CACHE_REDIS_PORT', 6379),
// The database to use when connecting to Redis.
'database' => env('CACHE_REDIS_DATABASE', 0),
]]);
And there you have it, matey! A quick jaunt through Laravelโs configuration settings. Now go forth and conquer your digital kingdom with well-configured dragons! ๐ฒ๐ช
Alrighty, buckle up for this rollercoaster ride through Laravelโs Passport wonderland! ๐๐ข
Token Time-Travel (No DeLorean Needed!)
By golly, out of the box, Passport dishes out access tokens that are as long-lived as a one-year subscription to a cat meme calendar. But fear not, you can adjust the tokenโs life expectancy like a time-traveling barber! ๐ฐ๏ธ
Just whip out your magic wand, or in this case, some good old PHP code, and cast these spells: tokensExpireIn, refreshTokensExpireIn, and personalAccessTokensExpireIn. These enchantments should be summoned from the mystical realm of your applicationโs App\Providers\AppServiceProvider class.
use Carbon\CarbonInterval;
**Sorcery Time!**
public function boot(): void
{
Passport::tokensExpireIn(CarbonInterval::days(15)); // 15 days, just enough time to binge-watch Stranger Things again.
Passport::refreshTokensExpireIn(CarbonInterval::days(30)); // A whole month of token refreshments!
Passport::personalAccessTokensExpireIn(CarbonInterval::months(6)); // 6 months, perfect for a season of The Crown.
}
Caution
Remember, the
expires_atcolumns in Passportโs database tables are as read-only as a librarianโs stern face, meant only for public display and not for tampering. When issuing tokens, Passport keeps the expiration info hidden within the magic amulet that is the signed and encrypted token. If you need to zap a token out of existence, revoke it instead! ๐
Now that weโve got our tokensโ lifetimes sorted, letโs move on to the next adventure! ๐
Unleashing Your Inner Model Maverick with Laravelโs Passport! ๐ค
Ahoy, partner! If you fancy customizing the models that Passport rides shotgun on in your Laravel herd, hereโs how you can lasso โem and break โem to your own beat.
First off, strap on your cowboy boots and saddle up with:
use Laravel\Passport\Client as PassportClient;
class Client extends PassportClient
{
// Don't forget to add your own wranglin' code here, partner!
}
Once youโve tamed and trained your new model steed, itโs time to let Passport know that the old oneโs been retired. You can do this by riding over to the AppServiceProvider corral and firing off a message:
use App\Models\Passport\AuthCode;
use App\Models\Passport\Client;
// (And so on, for all your models)
use Laravel\Passport\Passport;
/**
* Saddle up and prepare for service!
*/
public function boot(): void
{
// Swap out the old model horses for your new ones
Passport::useTokenModel(Token::class);
Passport::useRefreshTokenModel(RefreshToken::class);
Passport::useAuthCodeModel(AuthCode::class);
Passport::useClientModel(Client::class);
Passport::useDeviceCodeModel(DeviceCode::class);
}
Now, youโve got yourself a customized Passport herd! Ride โem, cowboy! ๐ต๐
Customizing Passport Routes: The Great Escape Plan ๐ดโโ ๏ธ
Ever felt like Passportโs routes are too vanilla for your pirate ship? Fear not, matey! In this section, weโll show ye how to customize those routes like a scurvy dog with PHP skills. ๐ฆ
First things first: ignore the routes registered by Passport by adding some Passport::ignoreRoutes magic to the register method of your applicationโs AppServiceProvider. ๐งโโ๏ธ
use Laravel\Passport\Passport;
/**
* Register any application services.
*/
public function register(): void
{
Passport::ignoreRoutes(); // Now Passport can't catch 'em all! ๐
}
Next, ye might want to copy the routes defined by Passport from its routes file and move โem over to your applicationโs routes/web.php file. ๐
Route::group([
'as' => 'passport.',
'prefix' => config('passport.path', 'oauth'),
'namespace' => '\Laravel\Passport\Http\Controllers',
], function () {
// Passport routes...
});
Donโt forget to tweak them to your heartโs content! ๐ญ Now your customized Passport routes can sail alongside your appโs other routes like the crew of a well-oiled ship! ๐ข
Alrighty then, letโs dive into the whirlwind world of OAuth2 via Authorization Codes! This is where your grandmaโs recipe book meets Silicon Valley โ a delightful fusion of cookies and coding.
First things first, we gotta school Passport on how to whip up our โauthorizationโ view. You can customize the entire baking process using all sorts of methods from the Laravel\Passport\Passport class, but weโll keep it simple and set the oven to preheat in the boot method of your applicationโs App\Providers\AppServiceProvider class.
use Inertia\Inertia;
use Laravel\Passport\Passport;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
// Set the view name to 'auth.oauth.authorize' (like calling out for Grandma's apple pie)
Passport::authorizationView('auth.oauth.authorize');
// Or, if you're feeling fancy, you can bake your own custom view using a closure!
Passport::authorizationView(
fn ($parameters) => Inertia::render('Auth/OAuth/Authorize', [
'request' => $parameters['request'],
'authToken' => $parameters['authToken'],
'client' => $parameters['client'],
'user' => $parameters['user'],
'scopes' => $parameters['scopes'],
])
);
}
Passport takes the wheel from here and sets up the /oauth/authorize route, which serves up that delicious authorization view. Your auth.oauth.authorize template should feature a form with two options: one for approving the authorization (the digital version of nodding your head in agreement), and another for denying it (just like saying โno thank youโ to Grandmaโs kale smoothie).
The forms will make POST requests to the passport.authorizations.approve route to approve the authorization, and DELETE requests to the passport.authorizations.deny route for the digital equivalent of shaking your head โno.โ Both routes require state, client_id, and auth_token fields in the request โ just like a recipe needs ingredients!
Now, letโs talk about managing clients. Itโs kinda like organizing the cookie jar for Passport. You can add, update, and delete clients as needed to keep your digital confectionery stocked with just the right flavors!
Alrighty, letโs get down to business! If youโre a developer building an app that wants to hang out with ours, itโs time to introduce yourself โ with a firm handshake and a well-crafted tuxedo (just kiddingโฆ sort of). To do this, you need to create a โclientโ which is like the digital equivalent of getting an invitation to our swanky soiree.
The process? Simple as pie (or maybe a bit more complex than that, but still pretty straightforward). You provide your appโs name โ no nicknames or aliases, we need to know who weโre dealing with โ and a fancy URI that we can redirect users to after theyโve given us the green light for authorization. Think of it as our way of saying, โWelcome aboard!โ
Now, letโs dive into the specifics:
First things first โ First Party Clients ๐ค
If your app lives on the same domain as ours (like siblings from the same parent company), youโve got a First Party Client on your hands. In our world, these are like the cool kids at school who already know everybody and have access to all the best parties (weโre just being friendly here).
To manage these special friends, head over to the Laravel Dashboard, and navigate to โConfigure -> Servicesโ. From there, click on the โCreate a new clientโ button. Fill out the necessary fields, and hit save! Youโve just scored an invitation to our exclusive event โ welcome aboard!
But wait, thereโs more! To make sure your app can access protected resources, youโll need to create an Access Token. This is like a golden ticket that allows your app to dance with us whenever it wants (as long as it plays by the rules). You can find more details on how to do this in the Access Tokens documentation.
Second fiddle โ Third Party Clients ๐ค๐ค
If your app is hanging out offsite (like that cool kid who moves to a new neighborhood), youโve got a Third Party Client on your hands. These folks are like the popular exchange student who wants to join our school dance (again, just being friendly here).
To manage these international guests, follow the same steps as First Party Clients, but with one key difference: when creating the client, make sure you select โThird-Partyโ in the Application Type field. Once everythingโs set up, your app can request an Access Token using OAuth 2.0 authorization code grant โ a fancy way of saying itโll have to dance through a few more hoops before we let it join our party (but hey, rules are rules).
And that, my dear developer friend, is how you manage clients in our Laravel-powered playground! Now go forth and create awesome applications! ๐๐ฅณ
Alrighty then! Letโs get this party started with Passport, Laravelโs magical OAuth2 unicorn! First off, if you wanna create a client, just yell โOpen Sesameโโฆ or rather, type php artisan passport:client in your terminal. This command is as sneaky as a narwhal in a china shop; itโll create first-party clients for your app or help test your OAuth2 functionality.
When you summon this command, Passport will quiz you about your client, just like a nosy neighbor asking what you got up to last Saturday night. After answering honestly (or not), itโll bless you with a shiny new client ID and secret. Just the ticket for all those late-night password swapping parties!
Now, if you wanna add more than one redirect URI for your client (cuz who doesnโt love options?), simply list them like theyโre your favorite flavor of ice cream when asked by the passport:client command. Just remember to URL encode any URIs that contain commas - โcause, you know, computers are picky!
https://third-party-app.com/callback,https://example.com/oauth/redirect
And there you have it! With these simple steps, youโre well on your way to creating clients that would make any snooty tech conference proud! (But donโt forget the mints!)
Ah, welcome dear developer! Letโs dive into the world of Laravelโs Third-Party Clients - where users become superheroes, and your application is their trusty sidekick! ๐
Since your appโs users canโt just snap their fingers to utilize the passport:client command (weโre still working on that magic wand feature), youโve got a superhero cape on - the createAuthorizationCodeGrantClient method of the Laravel\Passport\ClientRepository class! ๐ฆธ
use App\Models\User;
use Laravel\Passport\ClientRepository;
$user = User::find($userId);
// Creating an OAuth app client for our hero! ๐ฅ
$client = app(ClientRepository::class)->createAuthorizationCodeGrantClient(
user: $user, // Assigning the user as our superhero's alter ego! ๐ท๏ธ
name: 'Example App', // Our hero's secret identity for this mission! ๐ฆธโโ๏ธ
redirectUris: ['https://third-party-app.com/callback'], // The crime scene where our hero will return after saving the day! ๐
confidential: false, // No need for a secret hideout this time! ๐๏ธ
enableDeviceFlow: true // Our hero's prepared to battle evil on multiple devices! ๐ฑ๐ป
);
// Collecting all the OAuth app clients our superhero has saved from peril! ๐ก๏ธ
$clients = $user->oauthApps()->get();
The createAuthorizationCodeGrantClient method gives you a badge of honor - an instance of Laravel\Passport\Client. Display the $client->id as your superheroโs unique ID, and $client->plainSecret as the secret word that only they know! ๐คซ
Now go forth and protect your users from authentication chaos! ๐ช
Ahoy there, web-savvy pirates! Letโs set sail into the dazzling waters of Laravel token requestinโ. Shiver me timbers, itโs not just a dance move, itโs a key to securinโ yer API with an admiralโs grace! ๐ดโ๐
Requesting Tokens ๐
Ye might be wonderinโ, โWhat be this token lark, Capโn?โ Well, matey, itโs a secret handshake betwixt yer application and Laravelโs hearty API. Hereโs how ye can request one:
-
Sail over to the OAuth guard. This is the swashbucklinโ gateway that grants access to the treasured tokens. Itโs usually found nestled within
app/Providers/AuthServiceProvider.php. -
Register the OAuth Guard. Yar! Once ye reach the AuthServiceProvider, grab a quill and add this line:
$this->registerPolicies([
'App\User' => \Illuminate\Contracts\Auth\Guard::class,
]);
This tells Laravel which policies should be used for who. In this case, weโre tellinโ โer to use the OAuth Guard for users in our application.
- Set sail for the AuthManager. Aye, matey! Now itโs time to navigate to
app/Providers/AuthServiceProvider.phpagain and find theboot()method. Itโs where yeโll create a new instance of the OAuth guard. Hereโs how:
$this->app['auth']->extend('oauth', function ($app) {
return \Illuminate\OAuth\Facades\Oauth::createUsingProvider(config('services.passport'));
});
This bit of code sets up an OAuth guard with the Passport configuration settings from config/services.php. Swab the deck, as itโs ready to set sail!
- Arm thyself with the Passport. Aye-aye, Capโn! Now that ye have yer trusty OAuth guard, letโs get a hold of a token. First, fire up
App\Http\Controllers\Auth\LoginController. Then, in thelogin()method, add this line:
if (! $request->hasValidCredentials()) {
return $this->sendFailedResponse($request);
}
$credentials = $request->only(['email', 'password']);
$tokenResult = $this->guard()->attempt($credentials);
// If the login is successful, we will retrieve the user's OAuth token and
// create a fresh OAuth client instance for them on the fly. The OAuth
// client, user name, and token are stored in the session so that Laravel
// can authenticate the user and remember them until they sign out (when
// they opt-in to the "Remember Me" cookie).
if ($tokenResult) {
$request->session()->regenerate();
$user = $this->guard()->getUser();
$token = $user->createToken('Personal Access Token');
// Add a 'token' event to the user...
event(new AuthSuccess($user, $token));
}
This code handles the login process and creates an OAuth token for yer user.
- Swab the deck. Ahoy, matey! Now that ye have a solid grasp of requestinโ tokens, itโs time to put yer newfound skills into action and secure yer API like a true swashbuckler! Sail onwards, brave adventurer! ๐ดโโ ๏ธ
Ahoy there, coding cowboy! Once youโve wrangled up a client and saddled them with an ID and secret, they can gallop their way to your saloon for an authorization code and access token. But first, letโs lasso them onto your applicationโs /oauth/authorize corral with this here rope of PHP:
Use yer old trusty Request and Str classes, partner!
Route::get('/redirect', function (Request $request) {
Lasso a fresh $state using Str::random(40), just to keep things spicy.
Tie up the following query like a burro with http_build_query:
[
'client_id' => 'your-client-id',
'redirect_uri' => 'https://third-party-app.com/callback',
'response_type' => 'code',
'scope' => 'user:read orders:create',
'state' => $state,
// 'prompt' => '', // "none", "consent", or "login"
]
Now, hitch this query onto the `/oauth/authorize` route of your Passport-run saloon:
redirect('https://passport-app.test/oauth/authorize?'.$query)
});
Now, about that prompt parameterโitโs like a cowpokeโs hat at the saloon door. Set it to none, and your Passport pal will throw down an auth error if a rider ainโt already logged in. If you set it to consent, theyโll always display the authorization approval screen, even if theyโve granted all those juicy scopes before. And when you set it to login, well, theyโll always make a new cowboy re-log in, even if theyโre already sitting at the bar with a beer.
If you forget to put on that prompt hat, your Passport pardner will only ask for authorization if the rider ainโt previously authorized for those scopes.
Note
Donโt go trying to reinvent the wheel hereโthe
/oauth/authorizecorral is already set by Passport. Leave that job to the horse wranglers.
Now, how does a cowboy approve this request? Letโs say our client gets directed to your saloon and grants accessโyouโll need to grab that authorization code and access token, so donโt forget to saddle up them route handlers! Stay tuned for the next chapter of our Laravel saga: โCatching a Cowboyโs Credentialsโ!
Alrighty then! Letโs dive into the thrilling world of Laravel Passport, where authorization requests are as exciting as a rollercoaster ride at Six Flags (but without the stomach-churning drops).
When a request for approval comes knocking, Passport will react like a seasoned bouncer at a high-end club: itโll check out the prompt parameter (if available) and might even flash a friendly โApprove or Denyโ sign to the user. If they give the green light, theyโll find themselves back at the redirect_uri specified by the rambunctious application that initiated this whole shindig. Just remember, the redirect_uri needs to match the redirect URL used during client creation โ otherwise, itโs like trying to sneak into a VIP section with a regular ticket!
Now, there may be instances when you want to cut through the line, like when youโre authorizing a first-party client. In such cases, you can pull off an elegant dance move called โextending the Client modelโ and defining a skipsAuthorization method. If this method returns true, the client will get instant access and the user will be whisked back to the redirect_uri without waiting for the authorization prompt โ unless, of course, the application has explicitly asked for a prom date via the prompt parameter!
<?php
namespace App\Models\Passport;
use Illuminate\Contracts\Auth\Authenticatable;
use Laravel\Passport\Client as BaseClient;
class Client extends BaseClient
{
/**
* Determine if the client should skip the authorization prompt.
*
* @param \Laravel\Passport\Scope[] $scopes
*/
public function skipsAuthorization(Authenticatable $user, array $scopes): bool
{
return $this->firstParty(); // If this client is a first-party one, let's cut through the line!
}
}
Now that weโve got the approval process down pat, letโs move on to the next chapter: requesting tokens and converting authorization codes into access tokens. But hey, donโt worry โ weโll save that for another time, โcause itโs about as exciting as watching paint dry (but in a good way)!
Jump over here if youโre feeling particularly adventurous.
Alrighty, buckle up! Weโre about to embark on a whirlwind journey through Laravel land where the OAuth fairies sprinkle magic dust and authorization codes transform into shiny access tokens!
First off, letโs talk about the moment of truth when your user grants permission for your app to access their secrets (we wonโt ask, we promise). They get redirected back to you, and itโs time to play detective! You must verify the state parameter against the one stored prior to the redirect. If they match like long-lost twins at a family reunion, then itโs showtime!
Hereโs where things get really exciting: issue a POST request with all the flair of a late-night infomercial. This request goes to our Passport headquarters for an access token (we hope theyโre ready with the popcorn). The request should include the authorization code that your app sent over when the user said โyes, I trust you.โ
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
Route::get('/callback', function (Request $request) {
// This is where the mystery begins!
$storedState = $request->session()->pull('state');
$receivedState = $request->state;
if ($storedState !== $receivedState) {
throw new InvalidArgumentException("State value mismatch, it's like a magic trick gone wrong!");
}
// Time to make that request!
$response = Http::asForm()->post('https://passport-app.test/oauth/token', [
'grant_type' => 'authorization_code',
'client_id' => 'your-client-id',
'client_secret' => 'your-client-secret',
'redirect_uri' => 'https://third-party-app.com/callback',
'code' => $request->code,
]);
// And now for the grand finale... the access token!
return $response->json();
});
Once youโve made your request, the /oauth/token route will send back a JSON response with the precious trio: access_token, refresh_token, and expires_in. The latter tells you when the access token will expire (donโt worry, weโll remind you).
Note
We donโt want you to miss this ride, so the
/oauth/tokenroute is pre-defined by Passport. No need for manual labor here, just sit back and enjoy the show!
Now that weโve got our access token, itโs time to learn how to manage these tokens like a pro! (Stay tuned for our next episode where we teach you how to keep them organized in your very own token vault!) ๐ฏ๐๐โจ
Token Tussle: Keeping Your Users Connected (and Amused)!
In the wild world of Laravel Passport, itโs essential to keep track of your usersโ authorized tokens. Why, you might ask? Well, imagine a digital party where your users are dancing with third-party apps โ wouldnโt you want a dance floor monitor to ensure no one is left twirling solo or tripping over expired invitations?
Letโs cut the jive and get down to code! Hereโs how to corral those tokens:
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Carbon;
use Laravel\Passport\Token;
$user = User::find($userId);
// Let's round up all the valid tokens for this user...
$tokens = $user->tokens()
->where('revoked', false) // Only those still in good standing, please!
->where('expires_at', '>', Carbon::now()) // No time-traveling tokens allowed here!
->get();
// Time to introduce the third-party OAuth app connections...
$connections = $tokens->each(function (Token $token) {
if (!$token->client->firstParty()) { // A third-party is involved, so let's proceed!
return [
'client_id' => $token->client_id,
'scopes' => $token->scopes->unique()->values()->all(), // Scoping things out...
'count' => 1 // We found one token with this client, but who's counting? (Hint: You are!)
];
})->groupBy('client_id');
Now, isnโt that a smoother way to manage your usersโ tokens and keep them connected with all the right people? Just remember, itโs not just about maintaining connections โ itโs also about keeping things lighthearted and fun! ๐
Ahoy there, coding buccaneers! Sail with me into the realm of refreshing tokens, a vital port in every pirateโs journey through Laravelโs OAuth realm!
If your application is issuing access tokens that would make Captain Morgan himself shiver at their short lifespan, fear not! Your users can refresh their spirits and tokens by wielding the mighty refresh token granted during initial token issuance:
use Illuminate\Support\Facades\Http;
Swab the decks and hoist the jolly Roger, mateys! We're navigating to 'https://passport-app.test/oauth/token', a treasure trove of refresh token magic!
Here be the incantation:
```php
$response = Http::asForm()->post('https://passport-app.test/oauth/token', [
'grant_type' => 'refresh_token', // Ahoy, grant me a refreshed token!
'refresh_token' => 'the-refresh-token', // Speak the magic words...
'client_id' => 'your-client-id', // Prove your pirate identity, matey!
'client_secret' => 'your-client-secret', // The secret handshake for confidential clients only, don't forget it!
'scope' => 'user:read orders:create', // Yo ho ho! Expand thy treasure horizons!
]);
Return we must the response, ye scallywags, to claim your freshly minted tokens:
```php
return $response->json();
In this bounty-filled response, ye shall find three prized attributes: access_token, refresh_token, and expires_in. The expires_in attribute, marked by the ominous ticking of a time bomb, holds the number of seconds until the access token sets sail beyond the horizon.
Now, off you go, refreshed and ready to continue your Laravel OAuth adventures! Remember: always keep an eye on those expiration times, or risk ending up in Davy Jonesโ Locker without a treasure map!
Un-Tokening Your Tokens! ๐๐
Are your tokens causing more trouble than theyโre worth? Fear not, my friend! Laravel Passport has got your back with some nifty un-tokening techniques thatโll leave you chuckling and secure in no time! ๐
First off, letโs say you want to kick one token to the curb. No problemo! Just use the revoke method on the Laravel\Passport\Token model:
use Laravel\Passport\Passport;
use Laravel\Passport\Token;
$token = Passport::token()->find($tokenId);
// Time to say goodbye to that access token ๐๐ผ
$token->revoke();
But wait, thereโs more! If you want to ditch a refresh token along with its access buddy, donโt hesitate to use the revoke method on the Laravel\Passport\RefreshToken model:
// Revoke the token's refresh token...
$token->refreshToken?->revoke();
Feeling extra vindictive? If you want to boot all of a userโs tokens out into the cold, you can use a little loop magic:
// Revoke all of the user's tokens...
User::find($userId)->tokens()->each(function (Token $token) {
// Bye bye, token! ๐๐ผ
$token->revoke();
// And its refresh token too, for good measure! ๐๐ผ๐
$token->refreshToken?->revoke();
});
Now thatโs what I call a clean sweep! ๐ช๐ผ With these un-tokening techniques up your sleeve, you can rest easy knowing that your Laravel Passport is secure and the laughter never stops! ๐ฅณ๐ป
Ahoy there, code pirates! Time for a jolly tidy-up! ๐งนโจ
When your access tokens have been swabbed overboard (revoked) or expired faster than a salted anchovy on a sunny deck, you might find yourself with more seaweed in the boat than sailors. But fear not, for our trusty shipmate, Passport, has got your back!
To remove these unwanted seaweed tokens from your database, just shout this command at the nearest terminal like a true seafaring coder:
php artisan passport:purge
This one simple command will scour your shipโs hold clean of those expired tokens quicker than you can say โShiver me tokens!โ ๐๐ช๐จ
Now, with a spotless database, you can hoist the Jolly Roger and sail on with a cheerful heart. Arr matey, code like a pirate! ๐ดโโ ๏ธ๐
Ahoy there! Buckle up, coders! Todayโs adventure takes us to the world of token management in Laravel land. You see, just like a busy bartender clearing out glasses at closing time, we need to keep our digital tavern tidy by purging those revoked and expired tokens, auth codes, and device codes.
Ready for the magic spell? Let me introduce you to your new best friend: php artisan passport:purge! This powerful command is just what we need to keep our digital bar sparkling clean! Run this little charmer in your terminal, and watch as it sweeps through your authentication realm, banishing all those stale tokens, codes, and devices that have long since lost their luster.
And the best part? No mopping or sweeping required! So grab a brew, sit back, and enjoy the show โ but remember, a tidy tavern is a happy tavern!
Alright, my data-fueled friend! If youโve got a soft spot for digital security and an affection for well-aged tokens (who doesnโt?), then this little command is just the ticket for your next cyber-soiree. Letโs spice up that Passport party!
Gather โround, folks, and get ready to make some magical memories with your trusty terminal! Type in:
php artisan passport:purge --hours=6
Thatโs right! With a simple yet powerful incantation, weโre sending those expired tokens that are older than a 6-hour-old avocado on toast (or a freshly baked croissant, depending on your culinary preference) packing.
So, whether youโre looking to declutter your digital pantry or just want to keep things spicy with only the freshest tokens, this command will ensure that your Laravel Passport will always be on fleek! Happy token purging! ๐ฅ๐๐๐จ๐งน
Alrighty! Grab your cape (not that kind, weโre talking Laravel here), put on your super-developer thinking cap, and prepare for a token-purging adventure! When the need arises to get rid of those once-valuable but now revoked tokens, auth codes, and device codes in your Passport realm, itโs time to unleash the power of the command line!
To embark on this thrilling mission, simply summon the mighty artisan with a spell known as php artisan passport:purge --revoked. This magical incantation will send out a search party for all those stray revoked tokens in your application and ensure theyโre sent off into the digital abyss!
Remember, with great power comes great responsibility. Donโt use this command lightly; only when necessary should you let loose the forces of purge upon your Passport domain. Happy token-purging, brave developer!
Alright, letโs get this token party started (but only the expired ones!). Hereโs your invitation to clear the dance floor! ๐๏ธ๐บ๏ธ
To purge the expired tokens from your event, simply run this command:
php artisan passport:purge --expired
And just like that, youโve given a breath of fresh air to your token-filled ballroom. ๐ฅณ๐
Want to automate the cleaning process? Well, who doesnโt love a good housekeeper! Hereโs how to schedule a regular clean-up:
use Illuminate\Support\Facades\Schedule;
// In your routes/console.php file (just like a secret passageway)
Schedule::command('passport:purge')->hourly();
Now, every hour on the hour, your trusty token vacuum will sweep through and leave you with a sparkling clean dance floor! ๐งน๐ผ๐
Ahoy there, tech pirates! ๐ดโโ ๏ธ๐ด Letโs dive into the swashbuckling world of APIs and security with our trusty friend, the Authorization Code grant with โProof Key for Code Exchangeโ (PKCE)! ๐ก๏ธ
This isnโt your run-of-the-mill pirateโs hook, but a secure way to authenticate single page applications or mobile apps that are just as shifty and elusive as we are. ๐๐๐ดโโ ๏ธ Use this grant when you canโt trust your client secret to not end up walkinโ the plank, or to repel the threat of a sneaky attacker swiping your precious authorization code.
What sets PKCE apart from other methods? A dashing duo called the โcode verifierโ and the โcode challenge.โ Yar, these are like the secret handshake between your app and our API! Theyโll replace that client secret when you exchange the authorization code for an access token. ๐ค๐น
Now, letโs get down to the nitty-gritty of creating a PKCE grant client. Brace yourself for some serious swashbuckling action! ๐ด๐
Ahoy, matey! To create a PKCE grant client, ye must first create a new Laravel application and install the necessary dependencies. Once thatโs done, dive into your projectโs directory and start craftinโ a new service provider with the trusty Artisan command:
php artisan make:provider AuthPkceGrantServiceProvider
Next, open up your freshly baked service provider and register it within the providers array in config/app.php. Now, itโs time to create a new OAuth personal access client and implement the necessary methods for PKCE:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Laravel\Passport\Passport;
class AuthPkceGrantServiceProvider extends ServiceProvider
{
public function register()
{
Passport::createClient(config('services.oauth-pkce'), function ($app) {
return new OAuthPKCE($app);
});
}
}
Next, create a new OAuthPKCE class within your service provider directory and flesh it out with the essential PKCE methods:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Laravel\Passport\Bridge\AccessToken;
use Laravel\Passport\Client;
use Laravel\Passport\Passport as PassportClient;
class OAuthPKCE extends Client
{
public function __construct(array $options = [])
{
parent::__construct($options);
// Additional PKCE specific configuration
}
public function tokenEndpoint()
{
return route('oauth.access-token', ['client' => $this->id]);
}
protected function userIdentifier(): string
{
return (string) auth()->id();
}
// Implement additional PKCE specific methods here...
}
And voila! Youโve now created a PKCE grant client in your Laravel application. Now, itโs up to you to continue the swashbuckling adventure by implementing more PKCE specific methods and tacklinโ any other security challenges that may arise. Happy codinโ, matey! ๐ดโโ ๏ธ๐
Alrighty then! First things first, letโs get our PKCE-enabled client all dressed up and ready for the dance floor. Thatโs right, weโre about to tango with Laravelโs Authorization Code Grant, and we donโt want to step on anyoneโs toes without an invite.
To create this enchanting dance partner, youโll need to summon it with the magical passport:client Artisan command, but donโt forget to add the mystical --public option. Hereโs the incantation:
php artisan passport:client --public
Now that our client is all glammed up, itโs time to woo those tokens! Donโt worry; weโll leave the charm and wit to you and your code. ๐๐บ๏ธ
Alrighty, buckle up! Itโs time to dive into the thrilling world of token requesting โ a rollercoaster ride through the digital wild west of Laravel authentication.
Code Verifier/Code Challenge
First off, let me introduce you to our trusty sidekick, the code verifier. This is a randomly generated string that helps prevent some of those pesky bots from wreaking havoc on your pristine application. Think of it as an access code for the cool kidโs party where only genuine users are allowed in.
Now, to get ahold of this code verifier, youโll need to initiate what we like to call a โCode Challengeโ. It might sound like something out of a spy movie, but donโt worry, itโs much less suspenseful and involves way fewer exploding cars. Instead, it involves generating a code verifier and a code challenge. The code challenge is like the secret handshake between your application and the OAuth server โ it ensures theyโre communicating on friendly terms before exchanging any sensitive information.
To initiate thisCode Challenge/Code Verifier combo, you can use Laravelโs handy password_hash function to generate a random string for the code verifier:
use Illuminate\Support\Facades\Hash;
$codeVerifier = Hash::make(strtotime("now")); // or any other unique value
Now, you can pass this codeVerifier along with your request to the OAuth server and voila! Youโve just initiated a Code Challenge. The OAuth server will respond with an access token and a refresh token. But remember, this is only half of our adventure โ we still need to verify that the OAuth server has sent us the correct code verifier.
To do so, compare the codeVerifier youโve initiated with the one received from the OAuth server:
if (Hash::check($receivedCodeVerifier, $codeVerifier)) {
// Everything checks out! Proceed with the token exchange.
} else {
// Uh-oh! The code verifiers don't match. Something fishy is going on here.
}
And there you have it! Youโve just successfully navigated the Code Verifier/Code Challenge adventure in Laravel authentication land. Stay tuned for more heart-pounding escapades as we continue our journey through this wild west of digital security!
Ahoy there, intrepid Laravel devs! Itโs time to don our tinfoil hats and embark on a whimsical adventure in the land of Code Verifiers and Code Challenges. Now, before you say โEureka!โ remember this isnโt about the Ancient Greeks or Archimedesโ bath โ itโs all about security!
You see, when we dance the authorization grant waltz without a client secret, things can get a bitโฆ dicey. So, to ensure our token-requesting escapades remain as secure as Fort Knox (or, you know, the Laravel vault), we need to whip up a duo act: the enigmatic Code Verifier and the resilient Code Challenge!
The Code Verifier, our secret weapon, should be an opaque string of 43-128 characters, a veritable cocktail of letters, numbers, as well as your favorite internet barstool staples such as โ-โ, โ.โ, โ_โ, and the elusive โ~โ. You can think of it as a complex password thatโs been through one too many cocktails at the local speakeasy.
Now, to truly tickle our fancy, the Code Challenge must be draped in Base64 glory, complete with URL and filename-safe characters. Itโs like a well-dressed secret agent on a mission โ slick, efficient, and ready for action! Just remember to remove any pesky trailing โ=โ characters and strip it of any line breaks, whitespace, or other unwanted extras.
$encoded = base64_encode(hash('sha256', $codeVerifier, true));
$codeChallenge = strtr(rtrim($encoded, '='), '+/', '-_');
Now, isnโt that a smashing combination of code and humor? Just keep these tips in mind, and youโll be whirling around the dance floor like Fred Astaire, securely requesting tokens with the ease of a seasoned pro! ๐บ๏ธ๐๏ธ
Alrighty then! Letโs dive into the whirlwind world of Laravel OAuth redirection for authorization. First off, imagine youโve just baked a fresh client and youโre inviting them over for a dance party. But before they can groove, you need to verify their ID and that theyโre not a gate-crasher.
To do this, whip up a redirect request to your appโs /oauth/authorize route. Hereโs the disco moves in PHP:
Use Illuminate\Http\Request;
Use Illuminate\Support\Str;
Route::get('/redirect', function (Request $request) {
// Set up a secret state (like the password to get backstage)
$secretState = Str::random(40);
$request->session()->put('state', $secretState);
// Generate a fancy code verifier like "I'm here for the free drinks"
$codeVerifier = Str::random(128);
$request->session()->put('code_verifier', $codeVerifier);
// Convert the verifier into a code challenge, like turning a secret handshake into a hashtag
$codeChallenge = strtr(rtrim(
base64_encode(hash('sha256', $codeVerifier, true))
), '+/', '-_');
// Build the query, inviting the client to your app's authorization party
$query = http_build_query([
'client_id' => 'your-client-id',
'redirect_uri' => 'https://third-party-app.com/callback',
'response_type' => 'code', // We want a ticket to get in, not a hug!
'scope' => 'user:read orders:create', // Let's be clear about the privileges (reading user data and creating orders)
'state' => $secretState, // For safety, remember the secret state
'code_challenge' => $codeChallenge,
'code_challenge_method' => 'S256', // Using the most secure SHA-256 method to shake hands
// 'prompt' => '', // You can add "none", "consent", or "login" if you want more control over who gets in.
]);
// Send them a link to your app's authorization party
return redirect('https://passport-app.test/oauth/authorize?'.$query);
});
Now, when the client clicks on this magical link, theyโll be whisked away to your appโs authorization dance floor, where they can prove their worth and get their access token! Just remember to keep the secret state handy, or you might not recognize them once theyโre all decked out in disco attire. ๐๐ผโจ๐บ๐ผ๐
In the realm of digital dance floors, where applications and users tango in harmonious authorization, hereโs a jolly jaunt through the process of converting Authorization Codes into Access Tokens, aka the โCinderella Transformation.โ
First things first: if user agrees to your request (a rare and delightful occurrence), theyโll be whisked back to your application like a magical carriage. But before you get all giddy and open the champagne, itโs time for a bit of due diligence. Check the state parameter against the value stored prior to the redirectโitโs like making sure Cinderellaโs glass slipper still fits!
If the state matches (a fairy tale happily ever after), letโs get this party started! Time to send a charming, well-dressed POST request to your application asking for an access token. The party invitation should include:
- A dance card marked โgrant_typeโ and filled in with โauthorization_codeโ.
- Your own unique โclient_idโโthe secret code that identifies you on the dance floor.
- A formal โredirect_uriโโwhere the user was originally invited from.
- The โcode_verifierโโa shared secret between you and your suitor (the user).
- And last but not least, the shiny new โauthorization codeโ received upon the userโs approval.
Written in PHP, our charming dance partner could look something like this:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
Route::get('/ball', function (Request $request) {
$glassSlipper = $request->session()->pull('state');
$sharedSecret = $request->session()->pull('code_verifier');
throw_unless(
strlen($glassSlipper) > 0 && $glassSlipper === $request->state,
new InvalidArgumentException("Oops! Wrong glass slipper, try again!")
);
$danceInvitation = Http::asForm()->post('https://passport-app.test/oauth/token', [
'grant_type' => 'authorization_code',
'client_id' => 'your-client-id',
'redirect_uri' => 'https://third-party-app.com/ball',
'code_verifier' => $sharedSecret,
'code' => $request->code,
]);
return $danceInvitation->json();
});
And there you have it! The glamorous conversion of Authorization Codes to Access Tokensโthe ballroom equivalent of a fairy tale transformation. Enjoy your dance! ๐บ๐โจ
Alright, buckle up, folks! Itโs time to embark on a magical journey through the OAuth2 Device Authorization Grant โ the secret sauce that makes TVs and game consoles dance with joy (but not literally, theyโre not that advanced yet).
Imagine youโre a puppet master pulling strings in a dark room while your devices are the marionettes on stage. Thatโs essentially what weโre setting up here!
To get this party started, we need to enlighten Passport about our โuser codeโ and โauthorizationโ views โ think of them as our secret handshakes in this digital dance.
use Inertia\Inertia;
use Laravel\Passport\Passport; // It's like introducing your new best friend to the party
/**
* This is where the fun begins!
*/
public function boot(): void
{
// We tell Passport what our secret handshakes are called...
Passport::deviceUserCodeView('auth.oath.device.user-code');
Passport::deviceAuthorizationView('auth.oath.device.authorize');
// ...and we even show them a few magic tricks!
Passport::deviceUserCodeView(
fn ($parameters) => Inertia::render('Auth/OAuth/Device/UserCode') // *POOF* A view materializes!
);
Passport::deviceAuthorizationView(
fn ($parameters) => Inertia::render('Auth/OAuth/Device/Authorize', [
'request' => $parameters['request'],
'authToken' => $parameters['authToken'],
'client' => $parameters['client'],
'user' => $parameters['user'],
'scopes' => $parameters['scopes'],
])
);
// And so the magic continues...
}
Passport, being the magical genie it is, defines routes for these views automatically. Your auth.oath.device.user-code template should include a form that gets a โuser_codeโ from the passport.device.authorizations.authorize route โ think of it as the secret knock to enter the club.
Your auth.oath.device.authorize template should be chock-full of forms: one for approving authorization with a POST request to the passport.device.authorizations.approve route, and another for denying authorization with a DELETE request to the passport.device.authorizations.deny route. Both these routes expect state, client_id, and auth_token fields โ think of them as your VIP passes!
And voila! Youโve just set up the Device Authorization Grant, the ultimate party trick for your TVs and game consoles! Now letโs get this dance floor moving!
Unleashing the Token Tyrant: Creating a Device Authorization Grant Client
Ready to conquer the realm of token issuance? First, youโll need to crown your application as the King of Devices! This grand coronation can be achieved with the regal passport:client Artisan command, armed with the noble --device option. This magical spell will summon a first-party device flow enabled client and bestow upon you a regal client ID and secret for your kingdom:
php artisan passport:client --device
But fret not, dear third-party kings and queens! You too can join the device dance with the createDeviceAuthorizationGrantClient method on the illustrious ClientRepository class. This grand ballet will register your client as a beloved subject of the given user:
use App\Models\User;
use Laravel\Passport\ClientRepository;
$user = User::find($userId); // Remember, every king needs his subjects!
$client = app(ClientRepository::class)->createDeviceAuthorizationGrantClient(
user: $user, // Assign the user, no royal theft here!
name: 'Example Device', // A catchy name for your device, like "The Token Tyrant"
confidential: false, // Because, let's face it, you're a device, not a dragon with secrets!
);
Now, isnโt that a grand ballad of token issuance? Off to conquer the realm!
Alrighty, buckle up! Letโs embark on an exhilarating journey through the wild west of API authentication, where outlaws roam free and tokens reign supreme. In this here guide, weโll be talking about how to corral those tokens and tame them for your Laravel applications.
First up, weโve got the OAuth Dance of Death โ I mean, Device Authorization Code flow! This is a fancy way of saying โhow to get an access token by exchanging a code.โ Itโs perfect for mobile apps and other scenarios where you canโt redirect users to another page.
-
Register your application with an authorization server (the sheriff in town) and obtain your client ID and secret. Youโll need these like a cowboy needs his trusty six-shooter.
-
Redirect the user to the authorization serverโs URL with some parameters, including your client ID, a redirect URI, and scope (the permissions youโre requesting). This will prompt the user to log in and grant your application access to their resources.
-
The user logs in and grants your app access, and theyโll be redirected back to your application with an authorization code. This code is like a golden ticket โ hold on to it!
-
Swap that authorization code for an access token by sending a request to the authorization server with the code, client ID, secret, and redirect URI. This will return an access token, refresh token (if configured), and possibly an expiration time.
-
Store the access token safely (in a cookie, database, etc.) so you can use it to authenticate API requests in your Laravel application. And thatโs it! Youโve got yourself a shiny new access token to ride into the sunset with. Happy coding, partner! ๐ค
Ahoy there, coding cowboys and codettes! Once youโve saddled up your client and given it a unique ID (think of it as a trusty steedโs brand), you can hitch up your lasso and rope in a device code. Saddle up your browser or server, partner, and gallop over to your appโs /oauth/device/code corral - not for a wild mustang, but for a more civilized request with a good olโ fashioned POST.
use Illuminate\Support\Facades\Http;
$response = Http::asForm()->post('https://passport-app.test/oauth/device/code', [
'client_id' => 'your-client-id',
'scope' => 'user:read orders:create', // You're packing your six-shooter and ordering supplies!
]);
return $response->json();
Hold onto your Stetsons, because this will return a JSON response with attributes like device_code, user_code, verification_uri, interval, and expires_in. The expires_in attribute tells you how many seconds until the device code expires (think of it as the sheriffโs curfew). The interval attribute is your timer for checking back at the /oauth/token saloon to avoid rate limit errors โ much like waiting in line for beans and coffee.
Note
Donโt worry about fencing off that
/oauth/device/codecorral โ Passport has already taken care of it for you, cowpoke. You can just kick back, enjoy the view, and wait for that juicy device code to rope in.
Alrighty then! Letโs dive into the whimsical world of Laravel OAuth scaffolding, where enchanting devices frolic and your users dance with delight!
First things first, youโll need a magical device codeโimagine it as an invitation to a top-secret, fantasy ball. Once you have that code, summon the userโs attention and whisper in their ear: โHead over to the mystical verification_uri on another device, dear friend!โ
Now, if theyโre wondering where this hidden corner of the internet is, donโt fret! Youโve already waved your wand (or in Laravel terms, crafted a beautiful link) that leads them there. But wait! Thereโs more magic! They must enter the user_code into the enchanted portal to approve this authorization request. Think of it as sharing a secret password with the realm theyโre about to join.
So, in essence: grab your device code, beckon your user, and send them on a quest to the verification_uri. Once there, theyโll cast the spell of entering their user_code, unlocking access to the enchanted realm youโve prepared for them. Now isnโt that as exciting as a dragon chase through the forest? ๐ฅ๐ฒ
Ahoy there! Buckle up, dear developer friends, because weโre about to embark on a thrilling journey into the heart of Laravelโs OAuth Polling Token Request!
Picture this: youโve got your trusty pirate ship (consuming device), and youโre sailing in search of the elusive treasure chest (userโs response) that holds the keys to your kingdom (access token). However, the user is on a far-off island (separate device), so weโll need to send our trusty parrot (poll) to check if the treasure has been found.
First, letโs set the sailing interval ($interval) to 5, but remember, this pirate life ainโt for the impatient! Weโll keep sending the parrot to your applicationโs /oauth/token route until we get a response.
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Sleep;
$parrot = new Parrot('Poll'); // Because who doesn't love parrots?
$interval = 5;
do {
Sleep::for($interval)->seconds();
$response = Http::asForm()->post('https://passport-app.test/oauth/token', [
'grant_type' => 'urn:ietf:params:oauth:grant-type:device_code',
'client_id' => 'your-client-id',
'client_secret' => 'your-client-secret', // Keep your secrets safe, matey!
'device_code' => 'the-device-code',
]);
if ($response->json('error') === 'slow_down') {
$parrot->setMessage("Slow down, mate! Increase the sailing interval by 5.");
$interval += 5;
}
} while (in_array($response->json('error'), ['authorization_pending', 'slow_down']));
return $response->json();
If the user has granted us access, weโll return a JSON response with access_token, refresh_token, and expires_in attributes. The expires_in attribute tells us how many seconds until our precious access token walks the plank (expires).
So there you have it, matey! Now youโre ready to set sail on this OAuth adventure with a smile on your face and a song in your heart. Happy coding, pirates!
Ahoy there, Captain! Dive not into the murky waters of password insecurity; thatโs a treacherous route to embark upon. Instead, heed the beacon of OAuth2 Server and set sail for greener pastures with a grant type they heartily endorse!
The Password Grant, akin to a secret handshake among trusted parties (think: pirate crews), empowers your first-party clients โ like mobile marauders โ to seize access tokens using an email or username and password. This swashbuckling feature lets you issue these tokens securely without making your users walk the plank of the OAuth2 authorization code redirect flow.
To activate this dashing feature, call upon the enablePasswordGrant method in the boot event of your vesselโs trusty App\Providers\AppServiceProvider class:
/**
* Prepare the ship for battle!
*/
public function boot(): void
{
Passport::enablePasswordGrant(); // Ahoy matey, ye be ready to set sail!
}
Next up, letโs craft a client for our trusty password grant! Stay tuned for more swashbuckling adventures with Laravel Passport! Arrrr matey!
Alrighty, buckle up, my coding cowboy/cowgirl! Letโs get this password party started!
First things first, you gotta befriend the OAuth dancefloor and that means creating a password grant client. Donโt worry, it ainโt as fancy as it sounds. You just need to call upon your trusty Laravel Artisan by shouting out the passport:client command, but this time, with a twirl of a tassel (--password)!
php artisan passport:client --password
Now, whatโs an OAuth soiree without some fancy footwork? Letโs learn how to dance the password grant token waltzโฆ keep scrollinโ, partner! ๐๐บ๏ธ
Token Tango with Passport: A Whirlwind Romance! ๐โจ
Alright, buckle up, partner! Once youโve turned on the dance floor (grant) and donned your dancing boots (password grant client), itโs time to ask for a spin around the dancefloor (request an access token). You can initiate this by sending a sweet serenade (POST request) to our song (/oauth/token route).
Now, hold up! This dance floor is already registered with Passport, so no need to write a personal note for her yet. ๐
If everything goes smoothly, youโll end up in each otherโs arms (receiving an access_token and refresh_token in the JSON response). Just like any good dance, there might be some jive-talk involved:
use Illuminate\Support\Facades\Http;
$dance = Http::asForm()->post('https://passport-app.test/oauth/token', [
'grant_type' => 'password', // Yes, we're doing the Password Waltz tonight
'client_id' => 'your-client-id',
'client_secret' => 'your-client-secret', // Only if you're a secretive dancer... ๐คซ
'username' => 'taylor@laravel.com',
'password' => 'my-password',
'scope' => 'user:read orders:create' // Let's spice things up a bit, shall we?
]);
return $dance->json();
Attention
Access tokens are long-lived by default, but if you fancy setting the maximum access token lifetime, just take a peek at our secret dance moves! ๐บ๏ธ
Unleashing the Power of All Scopey Shenanigans! ๐
In the realm of Laravelโs Passport, when youโre swinging from the password chandelier or strutting your stuff with client credentials, you might feel like a superhero who wants to save the day by wielding the power of all available scopes. Fear not! For we have just the trick: summon the mystical * scope!
Once youโve invoked this cosmic force, the can method on your token will turn into an eternal โYes-manโ, forever nodding in agreement. But remember, this all-powerful scope can only be bestowed upon tokens that have been summoned via the enchanting incantations of password or client_credentials grants:
Use the Force, young Jedi! (I mean...)
use Illuminate\Support\Facades\Http;
Let's grab a magic potion (API response)!
$response = Http::asForm()->post('https://passport-app.test/oauth/token', [
'grant_type' => 'password', // Magic words to summon the token
'client_id' => 'your-client-id',
'client_secret' => 'your-client-secret', // Secret incantation for confidential clients only...
'username' => 'taylor@laravel.com',
'password' => 'my-password',
'scope' => '*', // The mystical * scope for unlimited powers!
]);
Now, go forth and conquer the OAuth realm with your newfound, all-encompassing scopey power! ๐๐โจ
Unleashing the Power of Multiple User Providers (AKA The Avengers of Authentication)
If your application is an Avengers-level team of user providers, youโre in luck! You can now choose which superhero (or provider) takes charge when it comes to password-based authentication.
To do this, summon the mystical artisan known as passport:client --password during your rituals at the command line. This ancient ceremony will conjure a client, but donโt forget to add the --provider option, specifying the name of the provider you want to lead the charge. This name should match a valid provider defined in your applicationโs config/auth.php configuration file.
Now that your chosen provider has been crowned as the password-protector supreme, itโs time to fortify your routes with some middleware superheroes. With these mighty allies by your side, you can ensure that only users from your selected provider will be granted access.
The Art of Custom Username Fields (AKA Whereโs Waldo?)
Sometimes, usernames arenโt where youโd expect them to be โ hidden like Waldo in a sea of fields. If your application stores usernames in a field other than the default username, donโt worry! Laravel has your back with customizable username fields.
To customize your username field, first, unleash the power of the AuthServiceProvider by overriding its boot() method. In this magical realm, cast a spell on the $hasCustomAuthIdentifiers, $username, and $fillable properties. Set them to true, the name of your custom username field, and an array containing the name of your custom username field, respectively.
Now, when users attempt to log in with their custom username, Laravel will know exactly where to look!
Unleashing the Power of Personalized Login! ๐ฆธโโ๏ธ๐ผ
Ah, dear user, if youโre here to customize your username field, we salute your adventurous spirit! ๐๐
By default, our beloved Passport, when it dances the authentication tango using the password grant, grabs the email attribute of your fabulous authenticatable model as its disco partner - a.k.a the โusernameโ. But fear not! Weโve got you covered if you fancy a change in partners. ๐บ๐
All you need to do is whip up a findForPassport method, and let it loose on your model. Hereโs a tantalizing recipe:
<?php
// Inside your magical App\Models folder... ๐ฉโจ
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticator; // We're the cool kids now!
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\Bridge\Client;
use Laravel\Passport\Contracts\OAuthenticatable;
use Laravel\Passport\HasApiTokens;
// ... and don your cape, because we're about to soar! ๐ฆธโโ๏ธ
class User extends Authenticator implements OAuthenticatable
{
use HasApiTokens, Notifiable;
/**
* Find the user instance for the given username.
*/
public function findForPassport(string $username, Client $client): self // Feel free to dance, partner! ๐๐
{
return $this->where('username', $username)->first();
}
}
And just like that, your user model will swirl and twirl to the beat of your customized username rhythm. ๐บ๐ Go forth and conquer! ๐ช๐
Alrighty, hereโs a fun take on customizing the password validation in Laravelโs Passport!
Custom Password Verification: The Secret Sauce to Your Appโs Security! ๐๐
When it comes to dancing the tango of authentication using the password grant, Passport gets all shimmied up and uses your modelโs password attribute like a pro to verify the incoming password. But what if your model doesnโt have a password attribute or you fancy customizing its validation logic? No worries! All it takes is defining a validateForPassportPasswordGrant method on your model, and voila! ๐ฉโจ
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\Contracts\OAuthenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable implements OAuthenticatable
{
use HasApiTokens, Notifiable;
/**
* Verify the user's password for the Passport password grant. (Because we can!)
*/
public function validateMyPassword(string $password): bool
{
// This is where the magic happens! ๐ฉโจ
return Hash::check($password, $this->password);
}
}
Now youโre ready to boogie down with custom password validation, while keeping your app secure and your users happy! Remember: when it comes to security, we donโt cut corners โ we dance them! ๐บ๏ธ๐๏ธ
The Daring Dash for Tokens: Implicit Grant! ๐๐โโ๏ธ
Warning, warning! Steer clear of those implicit grant tokens, mateys! Theyโre like last seasonโs fashion trends - outdated and best left behind. Instead, opt for the grant types that OAuth2 Server has been raving about.
The implicit grant is like its more cautious sibling, the authorization code grant, but without all that pesky exchanging of codes business. This grant is perfect for JavaScript or mobile apps where keeping client credentials under lock and key is about as easy as teaching a cat to play the violin. To enable this daring dash, drop by the boot method in your applicationโs App\Providers\AppServiceProvider class:
/**
* Party like it's 2019!
*/
public function boot(): void
{
Passport::enableImplicitGrant();
}
But before we get to the action, remember to register your application for this wild ride. That can be done using the passport:client Artisan command and the --implicit option:
php artisan passport:client --implicit
Now that the invitation has been sent, developers can join the party by requesting an access token from your application. Theyโll make a redirect request to your appโs /oauth/authorize route, which should look something like this:
use Illuminate\Http\Request;
Route::get('/redirect', function (Request $request) {
$request->session()->put('state', $state = Str::random(40));
$query = http_build_query([
'client_id' => 'your-client-id',
'redirect_uri' => 'https://third-party-app.com/callback',
'response_type' => 'token',
'scope' => 'user:read orders:create',
'state' => $state,
// 'prompt' => '', // "none", "consent", or "login"
]);
return redirect('https://passport-app.test/oauth/authorize?'.$query);
});
Info
A friendly reminder: the
/oauth/authorizeroute is already on Passportโs guest list. You donโt need to manually roll out the red carpet for it.
And that, dear friends, is how you pull off an Implicit Grant! Just remember to keep your client credentials as safe as Fort Knox, and always choose your grant types wisely. Happy token hunting! ๐ญ๐ต๏ธโโ๏ธ
Alrighty then! Letโs dive into the thrilling world of machine-to-machine authentication, shall we? Imagine your app as a suave secret agent, performing daring API maintenance tasks under cover of darkness. This is where the Client Credentials Grant comes in, acting as our agentโs stealthy Q-branch gadget.
But before our agent can start issuing those spy tokens, it needs to be properly outfitted with a Client Credentials Grant client. Donโt worry, this isnโt Mission: Impossible โ we just use the --client option of the trusty passport:client Artisan command:
php artisan passport:client --client
Next up, our agent needs clearance to access sensitive data. We assign the Laravel\Passport\Http\Middleware\EnsureClientIsResourceOwner middleware to a route, ensuring only authorized agents can access the precious goods:
use Laravel\Passport\Http\Middleware\EnsureClientIsResourceOwner;
Route::get('/orders', function (Request $request) {
// Access granted! Agent has valid token and is the resource owner...
})->middleware(EnsureClientIsResourceOwner::class);
Now, if you want to keep those orders under lock and key, you can restrict access to specific scopes by providing a list of the required scopes to the using method:
Route::get('/orders', function (Request $request) {
// Access granted! Agent has valid token, is the resource owner, and has both "servers:read" and "servers:create" scopes...
})->middleware(EnsureClientIsResourceOwner::using('servers:read', 'servers:create'));
And voila! Your appโs agent is now ready to navigate the treacherous waters of APIs, armed with a stealthy gadget and top-secret clearance. Just remember, with great power comes great responsibility โ use those tokens wisely! ๐๐ซ๐
Ahoy there, code pirates! Sail the seas of Laravel with us as we delve into the mystical art of token retrieval. Buckle up and prepare to be dazzled by our swashbucklingly humorous approach to this essential skill.
First off, letโs set sail for the oauth/token shore, a land youโll be visiting frequently. Remember, itโs not just any ordinary port, itโs the treasure trove of tokens!
use Illuminate\Support\Facades\Http; // In Laravel 6.x, use Illuminate\Foundation\Http\Facades\Http instead
// Here's where the pirate magic happens
$response = Http::asForm()->post('https://passport-app.test/oauth/token', [
'grant_type' => 'client_credentials', // This is our secret handshake with the token server
'client_id' => 'your-client-id', // Replace this with your very own pirate king ID
'client_secret' => 'your-client-secret', // And here, we keep our swords sharpened and secrets close to the chest
'scope' => 'servers:read servers:create', // We're not just here for a casual chat, we want full access to those servers!
]);
// Treasure awaits! Hoist the sails and grab your loot (access_token)
return $response->json()['access_token'];
And there you have it โ your very own treasure map to a bounty of access tokens. Now, go forth and conquer those servers with the power of Laravel at your fingertips!
Ahoy there, brave developers! Ever found yourself in a pickle, trying to navigate the treacherous waters of user authentication without a trusty compass? Fear not, for weโve got just the life jacket for you - Personal Access Tokens!
Imagine your users being pirates, eager to plunder your API treasure chest but too lazy to follow the traditional map-and-compass route. Now, who wouldnโt want to provide them a shiny parchment with a secret key, right? Thatโs exactly what weโre offering here!
Letting your users issue their own access tokens through your application interface can be as useful as a telescope on the Black Pearl, helping them explore your API like never before. Or perhaps itโs just a simpler approach to pirating, who knows?
[Yarr-NOTE] If your ship is heavily reliant on Passport for issuing personal access tokens, matey, consider hoisting the Jolly Roger of Laravel Sanctum - our lightweight first-party library for navigating API access token issues. Itโs like a compass that never points north, but always to the treasure!
Now, letโs set sail on creating a Personal Access Client!
Anchors Aweigh! To create a personal access client, youโll need to:
- Set up a new OAuth personal access client in your applicationโs database using the
make:authcommand. - Update your
forgemigration file to include the necessary columns for your new personal access client. - Register the client and its corresponding provider in the
app/Providers/AuthServiceProvider. - Modify your
routes/api.phpfile to accept requests for generating personal access tokens. - Create an API endpoint that handles token creation and revocation.
- Profit (or should we say, โArrr-profitโ)! Now your users can swab their decks and issue themselves those precious access tokens. Yarrr!
Alrighty then! Letโs get our digital fingers dancing on the keys, shall we? First things first โ youโre about to join the illustrious ranks of Laravelโs token-wielding titans. But before you can start issuing personal access tokens like a boss, you gotta create a personal access client.
Want to know how? Well, buckle up, buttercup! You can summon this magical entity by uttering the mystical incantation: php artisan passport:client --personal. If youโve already conjured up the passport:install command (you sorcerer, you), then this spell isnโt necessary.
php artisan passport:client --personal
And now, letโs delve into the arcane arts of customizing the user provider for good olโ PAT (Personal Access Token). Stay tuned for more enchantments! ๐คโจ๐
Unleashing Your Inner Superhero: Customizing User Providers! ๐
Ah, the glamorous world of Laravel authentication! Letโs dive right in and discuss customizing your User Provider, a fancy term for picking which superpower you want for your appโs login system.
If your app is a Justice League of multiple authentication user providers, then itโs time to decide who gets to wield Thorโs hammer! To do this, simply sprinkle a little magic when creating the client via the artisan passport:client --personal command by adding the --provider option. Think of it as choosing your preferred superhero origin story!
The provider name you provide should match a valid superpower defined in your applicationโs config/auth.php configuration file, AKA the blueprints for your superheroes. You can then use middleware to protect your route and ensure that only users from the provider associated with that particular superhero are allowed access.
Just remember: In the world of Laravel authentication, with great power comes great responsibility! ๐ฆธโโ๏ธ๐ฆธโโ๏ธ
Managing Personal Access Tokens: The Secret Identity of Your App ๐ต๏ธโโ๏ธ
Now that youโve customized your superhero lineup, letโs talk about managing their secret identities aka Personal Access Tokens. As a responsible superhero, itโs crucial to protect these tokens so they donโt fall into the wrong hands.
With Laravel, you can easily create and manage these tokens through various methods, like generating a new token for a user or revoking an existing one. So keep your app secure and prevent any villains from gaining unauthorized access! ๐ก๏ธ๐
Token Tango: A Jazzy Guide to Personal Access Tokens! ๐ผ
Ah, the rhythm of creating personal access tokens in Laravel - itโs like a dance! First things first, you gotta have a personal access client. Once thatโs sorted, letโs get our boogie on!
use App\Models\User; // Let's call him John Travolta ๐บ
use Illuminate\Support\Facades\Date;
use Laravel\Passport\Token;
John Travolta = User::find($userId);
// Stepping out without scopes...
$token = John Travolta->createToken('My Token')->accessToken; // Just a plain jane token! ๐
// Let's add some pizzazz with scopes...
$token = John Travolta->createToken('My Token', ['user:read', 'orders:create'])->accessToken; // Now we're dancing the 'Read User & Create Order Twist'! ๐บ๐
// Feeling bold? Let's go all out with all scopes...
$token = John Travolta->createToken('My Token', ['*'])->accessToken; // That's the 'All Scopes Boogie Woogie'! ๐บ๐
// Time to check out the tokens our John has in his wallet...
$tokens = John Travolta->tokens()
->with('client')
->where('revoked', false) // No revoked tickets please! ๐ซ
->where('expires_at', '>', Date::now()) // Only valid tickets, thanks! ๐๏ธ
->get()
->filter(fn (Token $token) => $token->client->hasGrantType('personal_access')); // And only personal access tokens, m'kay? ๐ค
Now thatโs what I call a token tango! Just remember to keep your moves smooth and your scopes in check. Happy dancing! ๐๐บ๐
Shielding Your Routes Like a Cyber Ninja! ๐ฅ
Defend Your App the Nerdy Way ๐
By the light of the monitor screen, we gather โround to discuss the art of securing our Laravel app routes. Fear not, dear developer, for this lesson shall be as entertaining as it is educational! ๐ค
Via Middleware ๐งฉ
You know those weird-named files in the app/Http/Middleware folder? Theyโre our cyber ninja armor, my friend! By binding these middleware to specific routes or entire application paths, we can ensure that all requests pass through our magical protection layers. ๐ซ
Authenticate a User (auth) ๐
Imagine youโre guarding the entrance to a high-security vault: only those with valid credentials can enter! Similarly, when applying the auth middleware to a route, Laravel will ensure that the user is logged in before theyโre allowed access. Itโs a perfect way to protect sensitive data or areas of your app. ๐
Authenticate and Authorize a User (can) ๐ก๏ธ
Now, letโs imagine youโre not just the gatekeeper, but also the boss of the secret base! With the can middleware, Laravel allows you to check if a user is authorized to access specific routes based on their role or permissions. Itโs like having a super-secret clearance level for your appโs most sensitive sections. ๐ต๏ธโโ๏ธ
Protecting Multiple Routes (RouteServiceProvider) ๐
If you want to protect multiple routes at once, no problem! Laravel provides the RouteServiceProvider, which lets you define middleware for entire controllers or route groups. Itโs like setting up a perimeter fence around an entire base instead of guarding each individual door. ๐ช
Custom Middleware ๐ฆธโโ๏ธ
And if none of the built-in middleware does the trick, Laravel lets you create your very own custom middleware! Write your own rules, implement your unique protection strategiesโthe skyโs the limit. Itโs like being a superhero with the power to protect your app however you want. ๐
So there you have it! Protecting routes in Laravel has never been so much fun. Go forth and guard your app like a cyber ninja, ensuring its securityโand yoursโat all times! ๐ปโ๏ธ
Via Magic Carpet Ride (a.k.a Middleware)
Passport comes equipped with a mystical authentication guard , that will verify those mysterious tokens on incoming requests from distant lands. Once youโve conjured up the api guard to be powered by the passport incantation, you only need to sprinkle the auth:api middleware (a potion of protection) on any routes you want to restrict access with a valid token:
Route::get('/wizard', function () {
// Only those under the spell of API authentication may pass this route...
})->middleware('auth:api');
> [!CAUTION]
> If you're utilizing the [client credentials grant ](#client-credentials-grant), it is advised to employ the enchanting [ `Laravel\Passport\Http\Middleware\EnsureClientIsResourceOwner` middleware](#client-credentials-grant) instead of the `auth:api` middleware to safeguard your routes.
<a name="multiple-authentication-guards"></a>
Now, if you've got multiple authentication guards (like a magical battle), you can prioritize them with ease! Just sort 'em like so:
```php
$app->routeMiddleware([
'web' => \Illuminate\Auth\Middleware\Authenticate::class,
'api' => \Illuminate\Auth\Middleware\Authenticate::class, // We want the API guard to be checked first!
]);
Remember, in a land of wizards and warriors, itโs always best to let the API guard ride shotgun!
Alright, letโs dive into the wacky world of Laravel authentication! ๐ฅณ
If your app has a cast of characters that require their own unique Eloquent models to log in (like a superhero squad or a reality TV show), youโll probably need to set up a guard configuration for each user type. This is like having separate bouncers at different clubs to ensure only the right people get in. ๐๐
Hereโs an example of how you can do this in your config/auth.php file:
'guards' => [
'superhero_nightclub' => [
'driver' => 'drink-till-you-slur',
'provider' => 'caped_crusaders',
],
'reality_tv_show' => [
'driver' => 'audience_participation',
'provider' => 'kardashians',
],
],
With this configuration in place, the following route will use the superhero_nightclub guard (which requires membership from the caped_crusaders user provider) to check whoโs trying to swing by:
Route::get('/batcave', function () {
// ...
})->middleware('auth:superhero_nightclub');
Note
For more information on using multiple user providers with Passport, check out the personal access tokens documentation and password grant documentation.
Remember, you can even pass the access token around like a virtual VIP wristband! ๐๐ผ๐ Just make sure your routes are equipped to handle it:
Route::get('/batcave', function (Request $request) {
// Check for access token here
if ($request->user()->hasAccessToken()) {
// ...
} else {
// Batman says: "I'm sorry, this conversation is now closed." ๐ฆ
}
})->middleware('auth:superhero_nightclub');
Happy coding! ๐๐๐
The Secret Dance of Access Tokens!
Ah, the thrilling world of Passport-protected routes! Now, hereโs where the magic happens, or should I say, the token dance!
Your API pals are required to strut their stuff and bring their access tokens to the dance floor, which is none other than the Authorization header in their request. Picture it as if theyโre saying, โExcuse me, dance floor, weโd like to enter, and hereโs our token - a Bearer token.โ
For those who canโt help but be drawn to the charm of Laravelโs Http Facade, I present you with this delightful demonstration:
use Illuminate\Support\Facades\Http;
// First, we flirt with our partner (Http Facade) and ask them to remember our name (accessToken)
$accessToken = "Your Secret Sauce Here"; // Replace me with your actual token, matey!
// Then, we attend the dance (make a request) by inviting them (Http Facade) to join us
// We remind them of our secret code words - 'Accept' and 'Authorization', and provide our token
$response = Http::withHeaders([
'Accept' => 'application/json', // I prefer my data in JSON format, if it's not too much trouble!
'Authorization' => "Bearer $accessToken", // And here is the secret key to unlocking the dance floor!
])->get('https://passport-app.test/api/user');
// After a night of dancing, we return home with memories (response) and our secrets (token) intact
return $response->json();
Now thatโs what I call a good dance!
Ahoy there, Captain API User! Ever found yourself in a pickle trying to manage permissions like a medieval feast, where everyone wants a piece of the action? Worry no more, matey, for weโve got just the thing - Token Scopes!
Imagine youโre running an e-commerce pirate ship (itโs all about the metaphors, see?) and not every swabbie on deck needs to be handling the cannonballs. Some can manage the treasure chest, others can keep an eye on the map, but nobody should be messing with the compass or the grog barrel without permission!
Enter Token Scopes, your new best mate for limiting actions third-party apps can perform on behalf of your noble shipmates (users). These scopes are like a secret treasure map that only allows specific permissions when granting authorization to access an account. So, instead of doling out full pirate privileges, you can set sail with more manageable roles, like โOrder Status Checkerโ or even the elusive โGrog Monitor.โ
Now, letโs dive deeper into those scopes! Yo ho ho, here be a guide to defining them:
- Defining Scopes: Itโs as easy as walking the plank (just kidding, itโs easier). You can define custom permissions in the Model class using the
scope()method. For example, in your Orders model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model {
// ...
public function scopeShipmentStatus($query) {
return $query->where('status', 'shipped');
}
}
- Using Scopes in Authorization: Once youโve defined your scopes, you can use them during the authorization process to grant or deny access based on these custom permissions. Hereโs how you might use it with Gate:
namespace App\Policies;
use Illuminate\Auth\Access\Response;
use Illuminate\Auth\Access\Gate as Gate;
use Illuminate\Database\Eloquent\Model;
class OrderPolicy {
use HandlesAuthorization;
protected $model = Order::class;
public function viewAny(User $user) {
return Gate::allows('view-any', $this->model);
}
// ...other methods...
public function shipmentStatus(User $user, Order $order) {
return Gate::allows('shipment-status', $order);
}
}
- Registering Scopes for Policies: To make your scopes available to policies, register them in the
registerPolicies()method of theAuthServiceProvider.
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Database\Eloquent\Model;
class AuthServiceProvider extends ServiceProvider {
// ...other methods...
protected function boot() {
$this->registerPolicies();
Model::registed(Order::class, function ($model) {
$model->bootQueryScopes();
});
}
}
Ah, the joy of crafting scopes in Laravelโs API world! Itโs akin to composing symphonies for your data, but with less violins and more tokens. Youโll find yourself orchestrating the access rights of your users through the venerable AppServiceProvider class.
Now, picture this: Youโre the gatekeeper at a very exclusive club (but with better coding practices). Instead of checking coats, youโre managing API keys and their access permissions. To do that, youโll be using Laravel Passportโs tokensCan method in the boot function of your classy AppServiceProvider.
/**
* We're not just serving drinks here, we're serving up scopes!
*/
public function boot(): void
{
// Our bouncer duties begin
Passport::tokensCan([
'user:read' => 'Retrieve the user info (Because who doesn't love a good gossip?)',
'orders:create' => 'Place orders (For those of you who are always hungry)',
'orders:read:status' => 'Check order status (So you know whether it's time to dance or wait in line)'
]);
}
And voila! Youโve transformed yourself into a sophisticated API bouncer, granting access to your club based on these scopes. Just remember, itโs all about balance: Too many scopes and you risk becoming the worldโs most chaotic disco; too few and you might as well be hosting a library book reading event. Happy scoping! ๐ค๐
Default Scopes: The Secret Ingredient to Your Passport Server! ๐น
Ever found yourself in a pickle when your clients forget to specify their secret sauce (I mean scopes)? Worry not, my friend! With Laravel Passportโs magical defaultScopes method, you can sprinkle the right mix of spices into your token without leaving your client high and dry.
To get started, head on over to your applicationโs AppServiceProvider class in the kitchen (aka App\Providers) and give it a little stir by adding these scopes:
use Laravel\Passport\Passport;
// Here's where the magic happens! โจ
Passport::tokensCan([
'user:read' => 'Grab some user info (don't forget to season it with a smile)',
'orders:create' => 'Place orders, but don't go wild now',
'orders:read:status' => 'Check if that order's ready for pickup',
]);
// And the cherry on top! ๐
Passport::defaultScopes([
'user:read',
'orders:create',
]);
And voila! Your Passport server is now seasoned to perfection, ready to serve up those delightful scopes whenever a client forgets their order. Just remember, with great power comes great responsibility โ so keep an eye on those orders and donโt let them go wild! ๐ฅด
Alright, buckle up, programmers! Today weโre diving into the ticklish topic of assigning scopes to tokens in Laravel Land. ๐ช๐
First things first: when youโre asking for authorization codes (you know, like when you ask your cat for permission to use its favorite chair), itโs important to remember that scopes can be your bestie! They help you manage access levels and keep your application secure. ๐๐ฆนโโ๏ธ
So, hereโs the fun part: to assign scopes to tokens, youโll need to create an Authenticate middleware and override its handle method. This is where all the magic happens! โจ๐ฉ
// app/Http/Middleware/Authenticate.php
public function handle($request, Closure $next)
{
// Check if the user has the required scopes for the token
$scopes = array_intersect($request->user()->getPermissions(), (array) $request->input('scope'));
if (!count($scopes)) {
// If the user doesn't have the required scopes, throw an exception
abort(403);
}
return $next($request);
}
Thatโs it! Now, every time a token is requested with some scopes, Laravel will ensure that the user associated with that token has those permissions. If not, it will throw a party for your error handling middleware (which, letโs face it, is always ready to dance). ๐๐บ
So next time youโre feeling like a cat on a hot tin roof when it comes to securing your application, remember the power of scopes! Theyโll help you navigate through those tricky access control situations with ease. ๐ฑ๐ฅ๐ช
Ahoy there, brave coder! Fancy yourself a dance with Laravelโs enchanting Authorization Code Grant? Well then, let me be your dance partner and guide you through the waltz! ๐๐บ
First off, when youโre hankering for an access token, remember to don your best manners. Thatโs right, ask politely by specifying your desired scopes as the scope query string parameter. The ballroom etiquette calls for it to be a list of scopes separated by space-time continuums (or simply spaces in simpler terms!).
Hereโs an example of how to make that perfect request:
Route::get('/redirect', function () {
$query = http_build_query([
'client_id' => 'your-client-id',
'redirect_uri' => 'https://third-party-app.com/callback',
'response_type' => 'code', // <-- You've been served, matey!
'scope' => 'user:read orders:create', // <-- Here's where the magic happens
]);
return redirect('https://passport-app.test/oauth/authorize?'.$query);
});
Now, off you go to the dance floor and show them what youโve got! Just remember to maintain a proper scope while you twirl and spin around Laravelโs ballroom! ๐๐ฉ๐ฅณ
Alrighty, buckle up, code cowboys and codettes! Letโs dive into the wild west of Laravel tokenery. ๐ค ๐๏ธ
If youโre ready to rope in some personal access tokens with the trusty App\Models\User modelโs createToken method, remember to lasso an array of your preferred scopes as the second rope around the corral:
$token = $user->createToken('My Token', ['orders:create'])->accessToken;
Yeehaw! Now youโre cooking with gas, partner. That little line of code will grant you access to create orders like a gunslinger at high noon. ๐๐
Oh, and donโt forget to check your scopes before you saddle up:
// Check the available scopes for a token
$user->tokens()->where('name', $tokenName)->first()->abilities;
Happy token wrangling, pardners! May your scopes always be within reach and your access tokens never hang by a thread. ๐๐ต๐ค
Token Tango: The Scope Shakedown! ๐บ๏ธ
Passportโs got the dance moves down! Weโve cooked up two swanky middleware thatโll ensure your incoming disco request is dancing with a token sporting a fancy scope. ๐จ
If you wanna check if a token can shake, rattle and roll with every single one of its scopes, then this is the routine for you! ๐ถ ๐บ๏ธ
To get started, simply inject the VerifyPersonalToken or CreateFreshApiToken middleware in your route file or controller, like so:
Route::middleware([
'auth:api',
\Illuminate\Auth\Middleware\Authorize::class
])->group(function () {
Route::get('/profile', function (Request $request) {
return $request->user();
});
});
And donโt forget to make sure youโve included the PassportServiceProvider in your app/Providers/AppServiceProvider.php. Itโs like a dance partner, and we all need one! ๐จโโค๏ธโ๐โ๐จ
Remember, it takes two to tango - so make sure youโve granted the appropriate scopes to your token before hitting the dance floor! ๐
Ahoy there, Captain! Navigating the seas of Laravel just got a tad more exciting with our trusty companion - CheckToken middleware. This nautical navigator is here to ensure your access tokens are as seaworthy as a pirateโs parrot.
To verify that your incoming requestโs access token is not just any old barnacle-encrusted thing, but rather a polished treasure chest brimming with the correct scopes, you can assign it to a route like so:
Arrr matey! Use Laravel\Passport\Http\Middleware\CheckToken and hoist the sails:
Route::get('/orders', function () {
// Arrgh, the access token has both "orders:read" and "orders:create" scopes...
})->middleware(['auth:api', CheckToken::using('orders:read', 'orders:create')]);
In this example, the CheckToken middleware is keeping a sharp eye on the /orders route, ensuring that only access tokens with both โorders:readโ and โorders:createโ scopes will be allowed to set sail. So, no more shady characters trying to swipe your grog without permission!
Alrighty, hereโs a dash of humor sprinkled into that Laravel doc!
Catch the Scope Creeps! ๐ต๏ธโโ๏ธ๐ฆนโโ๏ธ
Welcome to the undercover world of Laravel Passport where we catch those sneaky scopes with our top-secret middleware: Laravel\Passport\Http\Middleware\CheckTokenForAnyScope! ๐ต๏ธโโ๏ธ Assign this bad boy to a route and itโll ensure your incoming requestโs access token is packing at least one of the listed scopes.
use Laravel\Passport\Http\Middleware\CheckTokenForAnyScope;
// We're about to guard our precious orders like Fort Knox! ๐ฐ๐ฐ
Route::get('/orders', function () {
// Access token better have "orders:read" or "orders:create" scope in its entourage... ๐ค๐ต๏ธโโ๏ธ
})->middleware(['auth:api', CheckTokenForAnyScope::using('orders:read', 'orders:create')]);
Now, donโt go around playing spy games without knowing your scopes! ๐ต๏ธโโ๏ธ Check out the Scope Attributes section for more on those sly little fellows. Stay safe and keep those orders secure! ๐ก๏ธ๐ฐ
Scope Attributes: The Key to a Well-Oiled Passport!
If your Laravel appโs controller is more like a rowdy party and youโre using middleware attributes to keep the riffraff at bay, then youโll find our passport bouncer, AuthorizeToken, an absolute delight!
<?php
namespace App\Http\Controllers;
use Laravel\Passport\Attributes\AuthorizeToken as PassportBouncer;
#[PassportBouncer(['order-menus': 'read'])] // Only those with "read" access to order menus are allowed in.
#[PassportBouncer(['order-menus': 'create'], only: ['delivery-boys'])] // But if you're a delivery boy, you can create all the chaos you want!
class OrderMenuController
{
#[PassportBouncer(['order-menus': 'read', 'order-menus': 'create'], anyScopeAllowed: true)] // So long as they have access to either "read" or "create", let them in. No fuss, no muss!
public function index()
{
// Partygoer has the right to read or create order menus...
}
public function store()
{
// Partygoer can create AND read order menus! They're a real VIP!
}
}
By default, our Passport Bouncer demands all the scopes you throw at it. But if you set anyScopeAllowed: true, the request is granted when the token flashes at least one of your given scopes. Just like how a neon sign can get away with less clothing than the rest of Vegas! ๐โจ
Alright, letโs get this party started! Once your access token has slipped past security and made its grand entrance into your Laravel mansion (we call it an application), you can still give it the third degree with the tokenCan method. This nifty tool is hidden within the closeted, authenticated instance of your App\Models\User.
So when a request for orders comes knocking, you can investigate whether this sly token has the โorders:createโ scope by doing a little dance like this:
use Illuminate\Http\Request;
Route::get('/orders', function (Request $request) {
if ($request->user()->tokenCan('orders:create')) {
// Now we know it can create orders, let the good times roll!
} else {
// Sorry, pal. You don't have what it takes to order today.
}
});
Remember, tokenCan is the private investigator you never knew you needed in your Laravel world. Now, off with the gloves and letโs get down to business! (Just kidding, keep those hands clean.)
Alright, letโs dive into Laravelโs secret vault of access control! ๐โจ
First off, the scopeIds method is like a magic genie granting you a wish list of all defined IDs/names. Think of it as a whoโs-who in your applicationโs permissions world. To summon this wish list, simply cast this spell:
use Laravel\Passport\Passport;
Passport::scopeIds(); ๐ฆ๐ฉ๐ฎ
Next up, the scopes method is akin to an all-access pass to your appโs permission VIP lounge. This will give you an array of all those fabulous Laravel\Passport\Scope instances:
Passport::scopes(); ๐๐๐ผ
Now, the scopesFor method is a bit like having your own personal butler who serves you only the scopes you need. Just give it a list of IDs/names, and itโll return an array of those fancy Laravel\Passport\Scope instances:
Passport::scopesFor(['user:read', 'orders:create']); ๐๏ธ๐
Lastly, the hasScope method is like checking if your Cinderella dress has been invited to the royal ball. Use it to determine if a given scope has graced your app with its presence:
Passport::hasScope('orders:create'); ๐๐๐ฝ๐บ๐ฝ
The Incredible Journey of SPA Authentication ๐บ๏ธ๐ง
Building an API can be like composing a symphony, but with servers and code instead of violins and sheet music. And just as youโd want your own orchestra to dance to the same rhythm as the one you sell tickets for, your JavaScript app should groove to the same beat of your shared API!
In traditional jazz improvisation, manually passing an access token (think: a trumpet solo) to your application could get a little messy. But with Passport, weโre pulling out the autotune - itโll handle the token transmission for you, so you can focus on writing better code instead of solos! ๐ค
To set up this smooth setup, saunter over to your applicationโs bootstrap/app.php file and sprinkle in some Passport magic:
use Laravel\Passport\Http\Middleware\CreateFreshApiToken;
->withMiddleware(function (Middleware $middleware): void {
$middleware->web(append: [
CreateFreshApiToken::class,
]);
})
๐จ๐ถ Warning! ๐ถ Make sure you list CreateFreshApiToken as the grand finale in your middleware symphony, like a showstopping finale number at the end of the concert!
This middleware will craft a sweet laravel_token cookie to tag along with your responses. Itโs like giving your JavaScript app a backstage pass to bypass the ticket booth and access your API directly! ๐๏ธ๐ฅณ
The JWT token in this cookie has a lifespan as long as your session.lifetime configuration, meaning itโll keep grooving to the beat of your API for as long as you set it to! Since browsers are always eager to dance along, theyโll automatically send the cookie with every subsequent request, so you can dance away making requests to your API without even asking for that access token:
axios.get('/api/user')
.then(response => {
console.log(response.data);
});
Now, if you want to customize the name of this cookie (say, rename it from โlaravel_tokenโ to something more memorable like โpassportCookieโ), hop on over to your config/app.php file and edit the providers array:
'providers' => [
...
Laravel\Passport\PassportServiceProvider::class => [
'cookie' => 'your_custom_name', // replace with your desired name
],
],
Alright, letโs dive into the tantalizing world of Laravelโs Cookie Customization Circus! Ever felt your Laravel application was lacking a little pizzazz? Fret not, for we have just the ticket to jazz up that humdrum laravel_token cookie!
With our enchanting Passport::cookie method at your disposal, you can now rename your beloved cookie to something more befitting of your applicationโs personality. But be warned: this isnโt just a name change; itโs a transformation that will have your visitors whispering about the magical customizations theyโve stumbled upon in your website!
The secret to this metamorphosis is hidden within the boot method of your applicationโs AppServiceProvider. This cryptic chamber is where all the action takes place, and itโs time for you, the master puppeteer, to weave your magic:
/**
* When the lights go down at the beginning of the show...
*/
public function boot(): void
{
/**
* ...it's time to conjure up a new cookie name!
*/
Passport::cookie('custom_name');
}
And there you have it! Your Laravel application is now ready for its close-up, with a cookie thatโll leave everyone saying, โWho needs Cookie Monster when Iโve got this?!โ Donโt forget to wipe those cookie crumbs off your browsersโwe wouldnโt want anyone else stealing your thunder!
Alrighty, buckle up, web warriors! Letโs dive into the thrilling world of Cross-Site Request Forgery (CSRF) protection - a superhero cape for your Laravel applications.
Imagine youโre hanging out with friends, and one of them asks to borrow your wallet for a quick errand. You trust them, but just to make sure they donโt go on a wild spending spree, you put a secret password in the wallet. Thatโs what CSRF protection does - it adds a secret password (CSRF token) to your Laravel requests to ensure only your application can make changes.
Now, our friendly neighborhood Laravel has already provided some nifty JavaScript scaffolding, including an Axios instance, which is like having Spidermanโs web-shooters for making web requests. This superhero will automatically add the encrypted XSRF-TOKEN cookie value to the X-XSRF-TOKEN header on same-origin requests, leaving no room for mischief!
However, in a twist of fate (or a mistake), if you find yourself using the X-CSRF-TOKEN header instead, youโll need to switch to an unencrypted token by calling csrf_token(). But donโt worry, itโs just like having a backup plan โ always ready when you need it!
And thatโs your friendly guide to CSRF protection in Laravel. Now go forth and protect your applications from evil doers! (Or at least from unauthorized changes.)
Passportโs Party Time! ๐ฅณ
Get ready to dance the binary waltz, because Passport is throwing an event when it dishes out access and refresh tokens! ๐ You can groove to these tunes and prune or revoke other access tokens in your database like a disco king (or queen)!
| Event Name | Description | Dance Move |
|---|---|---|
Laravel\Passport\Events\TokenTwirl | Happens when a tokenโs born. ๐ถ | The Robot |
Laravel\Passport\Events\TokenDiscoDrop | Occurs when a token retires. ๐บ๏ธ | The Running Man |
Laravel\Passport\Events\TokenRe-Twirl | Happens when a new refresh token appears! ๐ช๏ธ | The Sprinkler |
Now, who needs a disco ball when youโve got Passport events to keep the party going? ๐บ๏ธ๐๏ธ๐ถ
Ahoy there, matey! Time to set sail on the seas of Laravelโs Passport testing!
First off, we got the actingAs method. This magical incantation not only lets you impersonate users but also bestows upon them some swashbuckling scopes! Hereโs how ya use it:
Shiver me timbers, load up ye arrays! First 'errrr's the user, freshly brewed by `User::factory()->create()`. Second be an array of scopes ye want to grant, in this case: `['orders:create']`.
Now fire the method and say "arrr" loud and proud, `Passport::actingAs(arrghh, arrgggh)`!
Matey, set sail with this code: `Passport::actingAs(User::factory()->create(), ['orders:create'])`.
First matey is our user, second be the scopes ye want, in our case 'orders:create'.
Now, if youโre testing for clients, donโt fret! We got actingAsClient, and it works just like actingAs, but with clients instead of users. Hereโs how to use it:
Arrr, now we got a client, freshly brewed by `Client::factory()->create()`. Same drill as before, second matey be an array of scopes ye want to grant, in this case: `['servers:read']`.
Now fire the method and say "arrr" loud and proud, `Passport::actingAsClient(arrghh, arrgggh)`!
Arrr, now we got a client, freshly brewed by `Client::factory()->create()`. Same drill as before, second matey be an array of scopes ye want to grant, in this case 'servers:read'.
Now fire the method and say "arrr" loud and proud, `Passport::actingAsClient(arrghh, arrgggh)`!
So there ye have it, matey! Now you can test like a true pirate, with scopes and all! Keep those tests shipshape, and remember: โYe who tests, wins!โ