Laravel 5.5中为JWTAuth指定非默认Guard实现学生表认证
Alright, let's walk through setting up the student guard for jwt-auth while keeping your default user guard intact. I'll break this down into clear, actionable steps:
config/auth.php First, we need to define the new guard and its provider in your authentication configuration. Open config/auth.php and make these additions:
Add the student guard to the guards array
This tells Laravel to use the jwt driver for student authentication, linked to a new provider:
'guards' => [ 'user' => [ 'driver' => 'jwt', 'provider' => 'users', ], // New student guard 'student' => [ 'driver' => 'jwt', 'provider' => 'students', ], ],
Add the students provider to the providers array
This maps the guard to your Student model and corresponding database table:
'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User::class, ], // New student provider 'students' => [ 'driver' => 'eloquent', 'model' => App\Models\Student::class, // Adjust this path to match your actual Student model ], ],
Optional: Password reset configuration (if needed)
If you plan to add password reset functionality for students, add this to the passwords array:
'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, 'throttle' => 60, ], 'students' => [ 'provider' => 'students', 'table' => 'student_password_resets', // You'll need to create this table if using 'expire' => 60, 'throttle' => 60, ], ],
Student Model Your Student model must implement the JWTSubject interface to work with jwt-auth. Here's how to set that up:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Tymon\JWTAuth\Contracts\JWTSubject; class Student extends Authenticatable implements JWTSubject { use HasFactory; // Define fillable fields based on your students table columns protected $fillable = [ 'name', 'email', 'password', // Add other student-specific attributes here ]; // Hide sensitive data from JSON responses protected $hidden = [ 'password', 'remember_token', ]; // Required methods for the JWTSubject interface public function getJWTIdentifier() { return $this->getKey(); // Returns the student's primary key } public function getJWTCustomClaims() { return []; // You can add custom claims here (e.g., ['role' => 'student']) if needed } }
Create a dedicated authentication controller (or add to an existing one) to handle student login. Here's a complete example:
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Tymon\JWTAuth\Facades\JWTAuth; class StudentAuthController extends Controller { /** * Handle student login request */ public function login(Request $request) { // Validate incoming credentials $request->validate([ 'email' => 'required|email', 'password' => 'required|string', ]); // Attempt to authenticate using the student guard $credentials = $request->only('email', 'password'); if (!Auth::guard('student')->attempt($credentials)) { return response()->json(['message' => 'Invalid email or password'], 401); } // Retrieve the authenticated student $student = Auth::guard('student')->user(); // Generate JWT token $token = JWTAuth::guard('student')->fromUser($student); return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth('student')->factory()->getTTL() * 60, 'student' => $student ]); } /** * Handle student logout */ public function logout() { Auth::guard('student')->logout(); return response()->json(['message' => 'Successfully logged out']); } }
Add these routes to routes/api.php (or web.php if using web-based auth):
use App\Http\Controllers\Auth\StudentAuthController; // Student login route Route::post('/student/login', [StudentAuthController::class, 'login']); // Protected student logout route Route::post('/student/logout', [StudentAuthController::class, 'logout'])->middleware('auth:student');
To restrict routes to authenticated students, use the auth:student middleware:
Route::group(['middleware' => 'auth:student'], function () { Route::get('/student/profile', function () { return auth('student')->user(); }); // Add other student-exclusive routes here });
That's all! You can now test the student login by sending a POST request to /student/login with valid email and password. The returned token will let students access protected routes, while your default user guard continues to work exactly as before.
内容的提问来源于stack exchange,提问作者Rahimjon Rustamov

