当前位置: 首页 > 工具软件 > Passport Bnet > 使用案例 >

Passport 密码模式

朱慈
2023-12-01

交流群 375462817

密码模式

准备工作

composer create-project --prefer-dist laravel/laravel laravel6
.env 数据库配置
修改数据库默认字符串长度
php artisan make:request BaseRequest // request 和 response 都是 json 格式
入口文件替换原生 Request 为 BaseRequest
php artisan make:controller PassportController
composer require laravel/passport
php artisan migrate // 创建表来存储客户端和 access_token 等
php artisan passport:install // 生成加密 access_token 的 key、密码授权客户端、个人访问客户端
Laravel\Passport\HasApiTokens Trait 添加到 App\User 模型中 // 提供一些辅助函数检查已认证用户的令牌和使用范围
composer require guzzlehttp/guzzle
// config/auth.php

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

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
        'hash' => false,
    ],
],
Passport::tokensExpireIn(now()->addDays(15)); // access_token 过期时间
Passport::refreshTokensExpireIn(now()->addDays(60)); // refresh_token 过期时间
Route::post('/oauth/token', '\Laravel\Passport\Http\Controllers\AccessTokenController@issueToken');


Route::post('/register', 'PassportController@register');
Route::post('/login', 'PassportController@login');
Route::post('/refresh', 'PassportController@refresh');
Route::post('/logout', 'PassportController@logout');


Route::get('test', function () {
    return 'ok';
})->middleware('auth');

登录、注册、刷新令牌、登出

<?php
namespace App\Http\Controllers;

use App\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PassportController extends Controller
{
    protected $clientId;
    protected $clientSecret;

    public function __construct()
    {
        $this->middleware('auth')->except('login', 'register', 'refresh');
        $client = \DB::table('oauth_clients')->where('id', 2)->first();
        $this->clientId = $client->id;
        $this->clientSecret = $client->secret;
    }

    protected function username()
    {
        return 'email';
    }

    public function register()
    {
        $this->validator(request()->all())->validate();

        $this->create(request()->all());

        return $this->getToken();
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255', 'unique:users',],
            'email' => ['required', 'string', 'email', 'max:255',],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    protected function create(array $data)
    {
        return User::forceCreate([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => password_hash($data['password'], PASSWORD_DEFAULT),
        ]);
    }

//    public function logout(Request $request)
//    {
//        auth()->user()->token()->revoke(); // 只会使 access_token 失效
//
//        return ['message' => '退出登录成功'];
//    }


    public function logout()
    {
        $tokenModel = auth()->user()->token();
        $tokenModel->update([
            'revoked' => 1,
        ]);

        \DB::table('oauth_refresh_tokens')
            ->where(['access_token_id' => $tokenModel->id])->update([
                'revoked' => 1,
            ]);

        return ['message' => '退出登录成功'];
    }

    public function login()
    {
        $user = User::where($this->username(), request($this->username()))
            ->firstOrFail();

        if (!password_verify(request('password'), $user->password)) {
            return response()->json(['error' => '抱歉,账号名或者密码错误!'],
                403);
        }

        return $this->getToken();
    }

    public function refresh()
    {
        $response = (new Client())->post('http://lishen.com/api/oauth/token', [
            'form_params' => [
                'grant_type' => 'refresh_token',
                'refresh_token' => request('refresh_token'),
                'client_id' => $this->clientId,
                'client_secret' => $this->clientSecret,
                'scope' => '*',
            ],
        ]);

        return $response;
    }

    /**
     * @param Request $request
     * @param Client  $guzzle
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    private function getToken()
    {
        $response = (new Client())->post('http://lishen.com/api/oauth/token', [
            'form_params' => [
                'grant_type' => 'password',
                'username' => request('email'),
                'password' => request('password'),
                'client_id' => $this->clientId,
                'client_secret' => $this->clientSecret,
                'scope' => '*',
            ],
        ]);

        return $response;
    }
}

使用 scope

// AppServiceProvider 注册 scope
Passport::tokensCan([
    'test1' => 'for test1',
    'test2' => 'for test2',
]);

// 注册中间件
'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,  // and
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,  // or

// 使用
->middleware('scopes:test1,test2');
->middleware('scope:test1,test2');
if (auth()->user()->tokenCan('place-orders')) {
    //
}

其他操作

Laravel\Passport\Passport::scopeIds(); // ["test1","test2"]

Laravel\Passport\Passport::scopes(); // [{"id":"test1","description":"for test1"},{"id":"test2","description":"for test2"}]

Laravel\Passport\Passport::scopesFor(['test1', 'check-status']); // [{"id":"test1","description":"for test1"}]

Laravel\Passport\Passport::hasScope('place-orders'); // false
 类似资料: