Laravel + VueJS 应用 Laravel Passport "message":"Unauthenticated." 问题

Posted

技术标签:

【中文标题】Laravel + VueJS 应用 Laravel Passport "message":"Unauthenticated." 问题【英文标题】:Laravel + VueJS Application Laravel Passport "message":"Unauthenticated." ProblemLaravel + VueJS 应用 Laravel Passport "message":"Unauthenticated." 问题 【发布时间】:2021-02-02 13:58:55 【问题描述】:

我开始开发 Laravel + VueJS 仪表板应用程序。但我有安全问题。 当我在未登录的情况下输入此 URL http://127.0.0.1:8000/api/user 时,我看到了请求答案。 我开始研究互联网以找到解决问题的方法。作为我研究的结果,我找到了 Laravel Passport。我按照official page 中的描述进行了设置,但没有成功。但应用程序不断响应。 "message":"未验证。"

UserController.php

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller


    public function __construct()
    
        $this->middleware('auth:api');
    

    /**  
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    
        return User::latest()->paginate(100);

    



    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    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  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    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 \Illuminate\Http\Response
     */
    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' => App\Models\User::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 App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;


class AuthServiceProvider extends ServiceProvider

    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
         'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    
        $this->registerPolicies();
        Passport::routes();
        Passport::personalAccessTokensExpireIn(now()->addDays(1));

        //
    


User.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

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));

根据我的研究,我认为一切似乎都是正确的。但我正在使用 Windows 上的 Wamp 服务器进行改进。你认为这会是个问题吗?我需要像这样对 htaccess 文件进行设置吗?

RewriteCond %HTTP:Authorization .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%HTTP:Authorization]

【问题讨论】:

您是否在该请求的标头中设置了 Bearer 令牌?? 我想我没有。你能告诉我怎么做吗?或者你能推荐一个教程吗? @HOSSAINAZADSHOHAG 【参考方案1】:

我在 Kernel.php 中添加了以下几行,我的问题得到了解决。

内核.php

  'web' => [
            \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
        ],

【讨论】:

【参考方案2】:

将带有 Bearer [您的令牌] 的 Authorization 标头添加到请求中并再次发送,然后检查它是否仍然返回 Unauthenticated。

【讨论】:

以上是关于Laravel + VueJS 应用 Laravel Passport "message":"Unauthenticated." 问题的主要内容,如果未能解决你的问题,请参考以下文章

Larave中CSRF攻击

如何在 laravel、vuejs 应用程序中设置 Paystack

Laravel + VueJS 应用 Laravel Passport "message":"Unauthenticated." 问题

laravel框架(blade模板引擎)

laravel框架总结 -- blade模板引擎

Larave使用composer安装无反应,提示“Changed current directory to C:/Users/Administrator/AppData/Roaming/Compose