Laravel 5.5 Passport OAth 认证

Laravel 5.5 Passport OAth 认证

Laravel 5年前 4071 0

今天做了个项目需要用到前后端分离,所以我写的后端代码都是以接口的形式给前端。研究了下发现在用户登录的时候 session 不起作用,于是使用 Laravel Passport 来解决这个问题。

本代码环境是 Laravel 5.5 LTS

创建项目

composer create-project laravel/laravel passport "5.5.*"

引入包

composer require laravel/passport=~4.0

Ps.如果报错的话请执行以下代码

composer require paragonie/random_compat=~2.0
composer require laravel/passport=~4.0

Laravel 5.4 以下需要配置 Service Provider

config/app.php

'providers' => [
    ....
    Laravel\Passport\PassportServiceProvider::class,
]

执行迁移文件

php artisan migrate

接下来,需要使用以下命令。生成秘密访问令牌所需的加密密钥。

php artisan passport:install

Passport配置

Model 配置

在 app 目录下 User.php 新增 Laravel\Passport\HasApiTokens

<?php

namespace App;

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

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',
    ];
}

AuthServiceProvider 配置

新增 Passport::routes 方法

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
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 修改如下:

return [
    ....

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

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

    ....
]

创建路由

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

Route::middleware('auth:api')->group(function () {
    Route::get('user', 'PassportController@show');
});

创建控制器

php artisan make:controller PassportController

复制以下代码:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class PassportController extends Controller
{
    /**
     * 用户注册
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|min:3',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);

        $token = $user->createToken('TutsForWeb')->accessToken;

        return response()->json(['token' => $token], 200);
    }

    /**
     * 用户登录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = [
            'email' => $request->email,
            'password' => $request->password
        ];

        if (auth()->attempt($credentials)) {
            $token = auth()->user()->createToken('TutsForWeb')->accessToken;
            return response()->json(['token' => $token], 200);
        } else {
            return response()->json(['error' => 'UnAuthorised'], 401);
        }
    }

    /**
     * 用户登录
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function show()
    {
        return response()->json(['user' => auth()->user()], 200);
    }
}

测试

php artisan serve

注册 Api,会返回一个 token 字符串

localhost:8080/api/register
name: yiqiao
email: [email protected]
password: 123456

登录 Api,会返回一个 token 字符串,主要就是拿这个返回的 token 来验证

localhost:8080/api/login

POST 请求
email : [email protected]
password : 123456

查看用户信息 Api 前端需要在请求头加些参数

'headers' => [
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '. $accessToken, (在Bearer 后面是有个空格的)
]
localhost:8080/api/user

{
    "user": {
        "id": 1,
        "name": "yiqiao",
        "created_at": "2019-05-15 07:29:22",
        "updated_at": "2019-05-15 07:29:22"
    }
}

详细信息

Passport OAuth 认证

原文: http://yiqiao.me/articles/15/laravel-55-passport-oath-certification

版权声明: 自由转载-非商用-非衍生-保持署名 (创意共享3.0许可证)