4.2. OAuth2 个人令牌模式认证

未匹配的标注

安装

我们使用laravel官方推荐的 Passport 进行 OAuth2 个人令牌模式认证:

$ composer require laravel/passport

运行迁移:

$ php artisan migrate

接下来让我们创建密钥:

$ php artisan passport:install

相关配置

<?php

namespace  App\Models;

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

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

接下来,你应该在 AuthServiceProvider 中的 boot 方法中调用 Passport::routes 方法。这个方法会注册必要的路由去颁发访问令牌,撤销访问令牌,客户端和个人令牌:

<?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();
        //
    }
}

最后,在 config/auth.php 配置文件中,你应该设置 api 权限认证守卫的 driver 选项为 passport:

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

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

添加路由

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| 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::prefix('v1')->name('api.v1.')->namespace('Api')->group(function() {

    Route::post('login', 'AuthorizationsController@login');//登陆
    Route::group([
        'middleware' => 'auth:api',
        'prefix' => 'auth'
    ], function ($router) {
        Route::post('logout', 'AuthorizationsController@logout');//退出登陆
        Route::post('user_info', 'AuthorizationsController@userInfo');//用户信息
    });
    Route::middleware('auth:api')->group(function ($router) {
        //这里存放需要通过验证的路由
    });
});

登陆相关

创建控制器,为了区分,我们把控制器放在 api 文件夹下:

$ php artisan make:controller Api/AuthorizationsController 

创建验证表单类:

$ php artisan make:request AuthorizationRequest

编写验证逻辑:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class AuthorizationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'username' => 'required|string',
            'password' => 'required|alpha_dash|min:6',
        ];
    }
}

迁移表中添加 phone 字段:

.
.
.
 $table->string('phone')->unique();
 .
 .
 .

运行迁移:

$ php artisan migrate

编写登陆逻辑:

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\AuthorizationRequest;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class AuthorizationsController extends Controller
{
    /**
     * @param AuthorizationRequest $request
     * @return array|string[]
     */
    public function login(AuthorizationRequest $request){
        $username = $request->username;

        //php7.0新东西,FILTER_VALIDATE_EMAIL为php自带的email过滤器
        filter_var($username, FILTER_VALIDATE_EMAIL) ?
            $credentials['email'] = $username :
            $credentials['phone'] = $username;

        //接收传来的值
        $credentials['password']=$request->password;

        //验证密码是否正确
        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => '账号或者密码不正确'
            ], 401);

        $user = $request->user();

        //生成token
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;
        $token->save();

        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);
    }
}

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
Jouzeyu
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 0
发起讨论 只看当前版本


暂无话题~