【发布时间】:2020-08-26 19:11:44
【问题描述】:
Laravel 没有用户标准的用户模型和用户表。我之前的程序员是这样计划的。我想添加jwt来分发api到项目中。
保存用户的表结构如下(表名client_users)
- @property int $id
- @property int|null $client_id
- @property 字符串|null $client_name
- @property 字符串|null $client_pass
- @property 字符串|null $client_phone
- @property 字符串|null $client_mail
- @property 字符串|null $api_token
- @property string|null $remember_token
- @property string|null $visible
- @property 字符串|null $deleted_at
首先,代替User模型使用的文件如下。
模型文件如下ClientUser.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
// use Illuminate\Foundation\Auth\User as Authenticatable;
// class User extends Authenticatable implements JWTSubject
class ClientUser extends Model implements JWTSubject
{
protected $connection = 'remoteMysql';
protected $table = "client_users";
protected $guarded = [];
}
配置授权文件如下。目录 config/auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\ClientUser::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
controller部分不同的是我们用客户电话和密码查询,而不是标准的邮箱密码
Api/AuthController.php文件如下
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['client_phone', 'client_pass']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
感谢您的建议和帮助。最好的问候。
【问题讨论】: