Laravel Passport始终如一。

时间:2019-03-20 21:31:03

标签: php laravel api laravel-passport

我已经建立了一个新的Laravel项目,并且打算使用Laravel Passport管理我的api的身份验证。

我已经可以登录和注册了,但是没有显示详细信息。

我正在测试使用邮递员向/api/details发送以下数据的邮寄请求:

Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjgwYmNhOGEzMTBmZjc2YTg0NTdkMTRjOTk0Y2VkNzMzODUwNDZkYjRhMzBhYjRjOTM0MWFlMGI4Y2I4MzRjMGU3MjY2ZjY5NjMwYTlmZjNmIn0.eyJhdWQiOiIxIiwianRpIjoiODBiY2E4YTMxMGZmNzZhODQ1N2QxNGM5OTRjZWQ3MzM4NTA0NmRiNGEzMGFiNGM5MzQxYWUwYjhjYjgzNGMwZTcyNjZmNjk2MzBhOWZmM2YiLCJpYXQiOjE1NTMxMTY4NjEsIm5iZiI6MTU1MzExNjg2MSwiZXhwIjoxNTg0NzM5MjYxLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.I66xwDmnc5O7NmaiXDYLiZATDGOBnicDgA94VhX8OKJ8wcRnZ9g0vgMIZRPWEmIXqxfdffQ8FR3LA3iB-nzVZhzFoPg8Bu17T739dU7fqjiM7t9dWSo1X_xUL-sumunppTQz-mAubQTS3wEXzfX1o72Z2eOd4pK9XxQCetDaGGkMwFqEmwr7FFddR9oITO3_KABGDiyE8LZDqzVMBDKEamOFdtLuMhIdJKuBFxetPJYF9WWQNXEvOOhS_o_XYISummFle52qnmpkDEVrR8QxYiy6CaNZN7KFHs2eTdb84ovNWGldzbBat6W8wBa4SuMz6rRgYmNjlbZpCHLNtxMOe7O1hziBZOHgpiw_bdRs4gD03AEsQk-_ADCfKTwaS6g3jcXNkkOcNITxaLdJEfVPH_d6iGftJXZtF_wv_JIpWEtxF--dN28wtI1Jvjf7DbdkOYpDYii-aXJDYLZFtMAb5_nzGS1ohjvoG3bNhn5jz2ugJ5IoB7cOwb22Kkc7jz37SCkAPzKvgUwNACIJ3lVfvToW7WlQDLo2nwubV9KMYVPoKc30CGMM5sdaqvQCPSQQTB3OQbG9bSIfA1uuPAaK7WKjPLOU1G3DavUc6kr0WhxcQS2wteuheKz3T_i9frrgUoknqHC5Tr-Y-DioXZP56CUOSXyqd9ABYEMzHLqyBt8

Content-Type: application/x-www-form-rurlencoded

Accept: application/json

我先运行登录并返回了上面的令牌,但我总是收到{"message":"Unauthenticated."}响应。

这是我的代码:

Api.php

<?php
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('login', 'API\UserController@login');
Route::post('register', 'API\UserController@register');
Route::group(['middleware' => 'auth:api'], function() {
    Route::post('details', 'API\UserController@details');
});

AppServiceProvider.php

<?php
namespace App\Providers;
use Laravel\Passport\Passport; 
use Illuminate\Support\Facades\Gate; 
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Carbon\Carbon;

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::tokensExpireIn(Carbon::now()->addYears(20));

        Passport::refreshTokensExpireIn(Carbon::now()->addYears(20));
    } 
}

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',
        ],
    ],
    /*
    |--------------------------------------------------------------------------
    | 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\User::class,
        ],
        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],
    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | Here you may set the options for resetting passwords including the view
    | that is your password reset e-mail. You may also set the name of the
    | table that maintains all of the reset tokens for your application.
    |
    | 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',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],
];

UsersController

<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\User; 
use Illuminate\Support\Facades\Auth; 
use Validator;
class UserController extends Controller 
{
public $successStatus = 200;
/** 
     * login api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function login(){ 
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            return response()->json(['success' => $success], $this-> successStatus); 
        } 
        else{ 
            return response()->json(['error'=>'Unauthorised'], 401); 
        } 
    }
/** 
     * Register api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function register(Request $request) 
    { 
        $validator = Validator::make($request->all(), [ 
            'name' => 'required', 
            'email' => 'required|email', 
            'password' => 'required', 
            'c_password' => 'required|same:password', 
        ]);
if ($validator->fails()) { 
            return response()->json(['error'=>$validator->errors()], 401);            
        }
$input = $request->all(); 
        $input['password'] = bcrypt($input['password']); 
        $user = User::create($input); 
        $success['token'] =  $user->createToken('MyApp')-> accessToken; 
        $success['name'] =  $user->name;
return response()->json(['success'=>$success], $this-> successStatus); 
    }
/** 
     * details api 
     * 
     * @return \Illuminate\Http\Response 
     */ 
    public function details() 
    { 
        $user = Auth::user(); 
        return response()->json(['success' => $user], $this-> successStatus); 
    } 
}

User.php

<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
  use HasApiTokens, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}

有人可以指出如何使它工作吗?

Laravel版本:5.8.5

2 个答案:

答案 0 :(得分:0)

在您的AuthServiceProvider.php中,您需要在

中包括Passport。
use Laravel\Passport\Passport;

,然后在boot()方法的末尾添加

Passport::routes();

在您的User.php中,您是否还添加了HasApiTokens特性?

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable, SoftDeletes;

答案 1 :(得分:0)

我不知道您的应用程序的性质,如果仅将其用于API,请查看config/auth.php并将defaults.guard更改为api

 'defaults' => [
    'guard' => 'api',           
    'passwords' => 'users',
],