Laravel Passport Multiauth

时间:2017-04-06 10:23:22

标签: php laravel api laravel-5.4 laravel-passport

我正在为2个前端应用程序(vue2 / mobile)开发API。一个使用User模型,另一个使用Admin模型(Laravel只是一个API)

我正在使用Laravel Passport来验证用户和管理员,我成功为用户提供了访问令牌,但我遇到了管理员的一些问题

所以我做了

1→创建了Admin模型

<?php

namespace App;

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

class Admin extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','role',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

2→创建了一个使用护照

的管理员
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
    'admin' => [
        'driver' => 'passport',
        'provider' => 'admins',
    ],
],

3→创建了用于授予管理员访问令牌的路由和控制器

Route::post('/oauth/token/admin', [
    'uses' => 'Auth\CustomAccessTokenController@issueUserToken'
]);

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use Psr\Http\Message\ServerRequestInterface;
use Laravel\Passport\Http\Controllers\AccessTokenController;

class CustomAccessTokenController extends AccessTokenController
{
    /**
     * Hooks in before the AccessTokenController issues a token
     *
     *
     * @param  ServerRequestInterface $request
     * @return mixed
     */
    public function issueUserToken(ServerRequestInterface $request)
    {
        $httpRequest = request();

        if ($httpRequest->grant_type == 'password') {

            $admin = \App\Admin::where('email', $httpRequest->username)
                               ->where('password', $httpRequest->password)
                               ->first();
            //dd($admin);

            return $this->issueToken($request);
        }
    }
}

4-&GT;我和Postman一起测试了

http://localhost:8000/api/oauth/token/admin

client_id:4
client_secret:M4QkLqhPkJ4pGL52429RipassQ3BOjKTJZe3uoWK
grant_type:password
username:admin@gmail.com
password:secret

//i'm getting
{
  "error": "invalid_credentials",
  "message": "The user credentials were incorrect."
}

//if i use the User model credentials 
username:user@gmail.com
password:secret

//i'm getting the access token 
{
  "token_type": "Bearer",
  "expires_in": 31536000,
  "access_token": "eyJ0eXAiOiJKV1Qi....",
  "refresh_token": "UI354EfJlVdmOhO...."
}

我真的很累,弄清楚出了什么问题

期待急需的帮助

谢谢

0 个答案:

没有答案