在laravel中, 可以用Passport扩展来实现Oauth2.0的接口身份验证。
可以让用户在第三方客户端登录账号。 但是大多数时候只需要用户直接在我们的客户端上登录即可, 这时候需要适合用Passport里面的Personal Access Tokens方式来实现。 下面记录下安装和使用过程。
在laravel项目根目录分别运行下面3行代码
//用composer安装passport
composer require laravel/passport
//生成依赖的数据表
php artisan migrate
//生成秘钥
php artisan passport:install
在User模型文件里(路径为App\Models\User或者App\User)里添加
use Laravel\Passport\HasApiTokens
use Illuminate\Database\Eloquent\Factories\HasFactory;
并且在类里面再次use一下
use HasApiTokens, HasFactory
修改后应该是下面的样子
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
在App\Providers\AuthServiceProvider文件中引入passport,
use Laravel\Passport\Passport;
然后在boot方法内启动Passport::routes, 如下:
public function boot()
{
if (! $this->app->routesAreCached()) {
Passport::routes();
}
}
Finally, in your application’s config/auth.php configuration file, you should set the driver option of the api authentication guard to passport. This will instruct your application to use Passport’s TokenGuard when authenticating incoming API requests:
最后,在config/auth.php 配置文件中,把api身份认证的驱动选项设置成Passport。
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
为了测试passport身份认证可用, 创建一个UserController
php artisan make:controller UserController
然后再UserController中补全下面的代码,用来测试注册和登录。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function register(Request $request){
$name=$request->input('name');
$email=$request->input('email');
$password=$request->input('password');
$check=User::where('email',$email)->first();
if($check){
return response()->json(['msg'=>'this email is already taken!']);
}
$r=User::create(['name'=>$name,'email'=>$email,'password'=>$password]);
if($r){
return response()->json(['msg'=>'register seccessful']);
}else{
return response()->json(['msg'=>'register failed']);
}
}
public function login(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
$user = User::where('email', $email)->where('password', $password)->first();
if ($user) {
$token = $user->createToken('Token Name')->accessToken;
return response()->json(['code'=>200,'msg' => 'login successful', 'token' => $token]);
} else {
return response()->json(['code'=>400,'msg' => 'login failed']);
}
}
}
加上api的路由
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Auth;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::middleware('auth:api')->post('/test', function (){
return '您已经登录了, 您的用户id是:'.Auth::id();
});
Route::post('/register',[UserController::class,'register']);
Route::post('/login',[UserController::class,'login']);
然后用JavaScript写一个ajax用来发送注册,登录已经获取资源的http请求。
<div>
<p id="show"></p>
<button onclick="register()">注册</button>
<button onclick="login()">登录</button>
<button onclick="access()">访问资源</button>
</div>
<script>
function register(){
xml=new XMLHttpRequest();
xml.open('post','http://xxx.xxx.xxx.xxx/api/register');
xml.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xml.setRequestHeader('Accept','application/json');
xml.onload=function(){
document.getElementById('show').innerHTML=xml.responseText;
};
xml.send('name=hello&email=hello11@qq.com&password=123');
}
function login(){
xml=new XMLHttpRequest();
xml.open('post','http://xxx.xxx.xxx.xxx/api/login');
xml.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xml.setRequestHeader('Accept','application/json');
xml.onload=function(){
var r=xml.responseText;
document.getElementById('show').innerHTML=r;
if(JSON.parse(r).code===200){
localStorage.setItem('token',JSON.parse(r).token);//把token存到浏览器
}
};
xml.send('email=hello@qq.com&password=123');
}
function access(){
var token=localStorage.getItem('token');
if(!token){
alert('请先登录!');
return false;
}
xml=new XMLHttpRequest();
xml.open('post','http://xxx.xxx.xxx.xxx/api/test');
xml.setRequestHeader('Authorization','Bearer '+token);
xml.onload=function(){
document.getElementById('show').innerHTML=xml.responseText;
};
xml.send();
}
</script>
测试后发现api接口的,注册,登录,身份验证功能正常。