Laravel 5.5:Laravel Passport应使用何种正确授权类型?
Hey there! Let's tackle your question step by step—you're absolutely on the right track: yes, you need to create Laravel Passport clients for each third-party job posting application that wants to interact with your API. Here's a breakdown of why, and how to implement it properly:
Core Context
Your scenario involves third-party apps acting on behalf of your existing registered users to submit job postings via your API. This fits perfectly with OAuth2's authorization flow, which Laravel Passport implements out of the box. Each third-party app needs a unique "client" identity in Passport to authenticate itself, and your users will grant it permission to act on their behalf.
Step 1: Set Up Laravel Passport (If Not Already Done)
First, make sure Passport is installed and configured in your Laravel app:
- Install the package:
composer require laravel/passport - Run migrations to create Passport's database tables:
php artisan migrate - Install Passport's encryption keys and default clients:
php artisan passport:install - Update your
Usermodel to implement theHasApiTokenstrait:use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; // ... rest of your model code } - Register Passport's routes in your
AuthServiceProvider'sbootmethod:use Laravel\Passport\Passport; public function boot() { $this->registerPolicies(); Passport::routes(); // We'll add scope definitions here later }
Step 2: Create a Passport Client for Each Third-Party App
For every third-party platform that wants to access your API, create a dedicated client. This lets you track, manage, and revoke access for individual apps as needed.
Choose the Right OAuth2 Flow
Since third-party apps are acting on behalf of your registered users, we recommend the Authorization Code Grant (the most secure and standard OAuth2 flow). Here's how to set it up:
- Run this command to create an authorization code client:
php artisan passport:client - Follow the prompts:
- Enter a name for the third-party app (e.g., "Acme Job Board")
- Enter the redirect URI: this is the URL on the third-party app where users will be sent after authorizing your app (e.g.,
https://acme-job-board.com/auth/callback)
- Save the generated
client_idandclient_secret—the third-party app will need these to authenticate.
If you absolutely need a simpler (less secure) flow (e.g., the third-party app collects your users' credentials directly), you can use the Password Grant by creating a client with:
php artisan passport:client --password
But note: this is not recommended for public third-party apps, as it exposes user credentials to the third party.
Step 3: Define Scoped Permissions
To restrict third-party apps to only the actions they need (in this case, creating job postings), define custom scopes in your AuthServiceProvider's boot method:
Passport::tokensCan([ 'create-jobs' => 'Submit job postings on behalf of a user', ]);
This ensures that even if a third-party app has a valid token, it can only access endpoints that require the create-jobs scope.
Step 4: Protect Your API Routes
Update your API routes in routes/api.php to use the auth:api middleware and enforce scopes where needed:
use App\Http\Controllers\JobController; // Protected route for creating jobs, requires the create-jobs scope Route::post('/jobs', [JobController::class, 'store']) ->middleware(['auth:api', 'scope:create-jobs']);
Step 5: Third-Party App Integration Flow
Here's how the end-to-end process will work for users:
- The user navigates to the third-party job posting platform.
- The third-party app redirects the user to your app's authorization page:
https://your-app.com/oauth/authorize?client_id=YOUR_CLIENT_ID&redirect_uri=THIRD_PARTY_REDIRECT_URI&response_type=code&scope=create-jobs - The user logs into your app (if not already logged in) and confirms they want to let the third-party app create jobs on their behalf.
- Your app redirects the user back to the third-party app's callback URL with an authorization
code. - The third-party app sends a POST request to your
/oauth/tokenendpoint with the code, client ID, client secret, and redirect URI to exchange it for anaccess_tokenandrefresh_token:curl -X POST https://your-app.com/oauth/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=authorization_code" \ -d "client_id=YOUR_CLIENT_ID" \ -d "client_secret=YOUR_CLIENT_SECRET" \ -d "redirect_uri=THIRD_PARTY_REDIRECT_URI" \ -d "code=AUTHORIZATION_CODE" - The third-party app uses the
access_tokenin theAuthorizationheader to submit job data to your API:curl -X POST https://your-app.com/api/jobs \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "title": "Senior Laravel Developer", "description": "We need an experienced Laravel dev...", // other job fields }' - When the
access_tokenexpires, the third-party app can use therefresh_tokento get a new one without requiring the user to re-authorize.
Key Notes
- Client Management: Use the Laravel Passport CLI or build a dashboard to manage your clients (revoke access, view usage, etc.).
- Security: Always use HTTPS for all API and authorization requests to prevent token interception.
- Scope Enforcement: Scopes let you limit what each third-party app can do—never grant broader permissions than necessary.
内容的提问来源于stack exchange,提问作者adam78

