Laravel 5.6如何将路由组设为公开?API注册路由权限问题
Hey there! Let's work through this guest route issue together. Since you're using Laravel 5.6 and JWT-Auth 1.0.0-rc.2, there are a few common pitfalls that might be blocking your /signup route from being accessible to unauthenticated users. Here's how to troubleshoot and fix it:
1. Check Your Route Group Structure
Most likely, you've accidentally nested your /signup route inside a route group that requires JWT authentication. Let's fix that:
Wrong Approach:
// routes/api.php Route::group(['middleware' => 'jwt.auth'], function () { Route::post('/signup', 'AuthController@signup'); // This is locked behind auth, which we don't want! // Other authenticated routes... });
Correct Approach:
Move the signup route outside the authenticated route group so it's accessible to guests:
// routes/api.php // Guest-accessible route first Route::post('/signup', 'AuthController@signup'); // Authenticated routes group Route::group(['middleware' => 'jwt.auth'], function () { // Your protected API routes go here });
2. Exclude Middleware If Using Global API Middleware
If your API routes are globally using the jwt.auth middleware (configured in RouteServiceProvider), you can explicitly exclude it for the signup route using withoutMiddleware:
// routes/api.php Route::post('/signup', 'AuthController@signup')->withoutMiddleware(['jwt.auth']);
3. Verify Your Controller's Middleware Settings
Don't forget to check your AuthController—if you've applied the jwt.auth middleware in the controller's constructor, you need to exclude the signup method from it:
// app/Http/Controllers/AuthController.php namespace App\Http\Controllers; use Illuminate\Http\Request; class AuthController extends Controller { public function __construct() { // Apply JWT auth to all methods EXCEPT signup $this->middleware('jwt.auth')->except('signup'); } public function signup(Request $request) { // Your user registration logic here } }
4. Double-Check JWT Middleware Registration
Just to be safe, confirm that JWT's middleware is properly registered in app/Http/Kernel.php:
// app/Http/Kernel.php protected $routeMiddleware = [ // ... 'jwt.auth' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class, 'jwt.refresh' => \Tymon\JWTAuth\Http\Middleware\RefreshToken::class, // Any other JWT middleware you're using ];
Since you mentioned an example route works, this is probably already set up, but it's worth a quick check to rule out typos.
Final Test
After making these changes, send a POST request to /api/signup (remember, API routes in Laravel 5.6 automatically prefix with /api unless you modified the route service provider) without a JWT token. It should now process the request without throwing an authentication error.
内容的提问来源于stack exchange,提问作者Mr. B.

