#php #laravel #vue.js #axios #laravel-passport
#php #laravel #vue.js #axios #laravel-паспорт
Вопрос:
Я начал разрабатывать приложение панели инструментов Laravel VueJS. Но у меня проблема с безопасностью. Когда я ввожу этот URL—адрес http://127.0.0.1:8000/api/user без входа в систему я вижу ответ на запрос. Я начал исследовать Интернет, чтобы найти решение проблемы. В результате моих исследований я нашел паспорт Laravel. Я настроил его, как описано на официальной странице, но мне это не удалось. Но приложение постоянно отвечает. {«сообщение»: «Не прошедший проверку подлинности».}
UserController.php
<?php
namespace AppHttpControllersAPI;
use AppHttpControllersController;
use IlluminateHttpRequest;
use AppModelsUser;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesAuth;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
}
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function index()
{
return User::latest()->paginate(100);
}
/**
* Store a newly created resource in storage.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function store(Request $request)
{
//return['message'=>'I have data'];
//return $request->all();
$this->validate($request,[
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
'password' => 'required|string|min:6'
]);
return User::create([
'name' => $request['name'],
'email' => $request['email'],
'type' => $request['type'],
'bio' => $request['bio'],
'photo' => $request['photo'],
'password' => Hash::make($request['password']),
]);
}
public function profile()
{
return auth('api')->user();
}
/**
* Update the specified resource in storage.
*
* @param IlluminateHttpRequest $request
* @param int $id
* @return IlluminateHttpResponse
*/
public function update(Request $request, $id)
{
$user = User::findOrFail($id);
$this->validate($request,[
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users,email,'.$user->id,
'password' => 'sometimes|min:6'
]);
$user->update($request->all());
return ['message' => 'update'];
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
return['message' => 'User Deleted'];
}
}
auth.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => AppModelsUser::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
AuthServiceProvider.php
<?php
namespace AppProviders;
use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider;
use IlluminateSupportFacadesGate;
use LaravelPassportPassport;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'AppModel' => 'AppPoliciesModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::personalAccessTokensExpireIn(now()->addDays(1));
//
}
}
User.php
<?php
namespace AppModels;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelPassportHasApiTokens;
class User extends Authenticatable
{
use HasFactory, Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'bio', 'photo', 'type'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Синтаксис запроса
axios.get("api/user").then(({ data }) => (this.users = data.data));
Из моих исследований, я думаю, все кажется правильным. Но я вношу свои улучшения с помощью сервера Wamp в Windows. Вы думаете, это будет проблемой? Нужно ли мне делать настройки в файле htaccess подобным образом?
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Комментарии:
1. Вы установили токен предъявителя в заголовке этого запроса??
2. Думаю, я этого не сделал. Можете ли вы сказать мне, как это сделать? Или вы можете предложить учебник? @HOSSAINAZADSHOHAG
Ответ №1:
Добавьте заголовок авторизации с предъявителем [ваш токен] в запрос и отправьте его снова, затем проверьте, возвращает ли он по-прежнему не прошедший проверку подлинности.
Ответ №2:
Я добавил следующие строки в Kernel.php и моя проблема была решена.
Kernel.php
'web' => [
LaravelPassportHttpMiddlewareCreateFreshApiToken::class,
],