如何使用中间件来授权我的laravel Restfull API



我正在使用laravel/passport,我想授权我的API端点然后我收到的结果声明路由(用户/登录名(未在邮递员中定义状态代码500

路线

路由::get('所有/用户','UserController@index'(->中间件("auth"(

控制器

{  
return new UserResource(User::findOrFail($id));
} 

用户模型

use LaravelPassportHasApiTokens;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;

class User extends Authenticatable
{
use Notifiable, HasApiTokens;

protected $fillable = [
'name', 'email', 'password','balance','phone'
];

protected $hidden = [
'password', 'remember_token',
]; 
}```
当您在web.php文件中调用Auth::routes()时,路由user/login在应用程序中声明。

返回该错误是因为您使用的是api路由,并且已经在其上调用了auth中间件

如果您想在未经授权的用户试图访问api时只返回401 unauthorized响应,则必须使用带有api保护的auth中间件。

请参阅下面的示例和正确代码:

Route::get('all/users', 'UserController@index')->middleware('auth:api');

最新更新