laravel passport学习笔记
视频
B站上的视频
注意了,开箱即用的认证字段是email字段,如果需要修改,App\User.php模型中加findForPassport方法,如下,findForPassport方法中,我用name字段认证
先看一下注册
public function register(Request $request){
$request->validate([
'username' => 'required|string',
'email' => 'required|string',
'password' => 'required|string',
]);
$res = User::create([
'username' => $request->get('username'),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password')),
]);
if ($res) {
$http = new Client();
// 发送相关字段到后端应用获取授权令牌
$response = $http->post('127.0.0.6/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => env('CLIENT_ID'),
'client_secret' => env('CLIENT_SECRET'),
'username' => $request->input('email'), // 这里默认传递的是邮箱
'password' => $request->input('password'), // 传递密码信息
'scope' => '*'
],
]);
return response($response->getBody());
}
}
登录
public function login(Request $request)
{
$request->validate([
'username' => 'required|string',
'password' => 'required|string',
]);
$http = new Client();
// 发送相关字段到后端应用获取授权令牌
$response = $http->post('127.0.0.6/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => env('CLIENT_ID'),
'client_secret' => env('CLIENT_SECRET'),
'username' => $request->input('email'), // 这里传递的是邮箱
'password' => $request->input('password'), // 传递密码信息
'scope' => '*'
],
]);
return response($response->getBody());
}
细心的你一定会发现上面的代码中’username’ => $request->input(‘email’),这里并不是写错了,因为默认是用邮箱号登录!!,如果你这里不是email则会发现获取时报错404,如果你需要验证的username,请在User模型中添加方法,当然你也可以验证name,或者其他字段,自己修改一下就行
public function findForPassport($username)
{
return $this->where('username', $username)->first();
为什么是加findForPassport方法呢?请看这位大佬的笔记
<?php
namespace App;
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;
use HasApiTokens;
/**
* 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',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* @param $username
* @return mixed
* 加上这findForPassport个方法来修改认证字段,我的改为了name,
*/
public function findForPassport($username)
{
return $this->where('name', $username)->first();
}
}