在ThinkPHP中,实现用户认证与授权可以通过以下步骤来完成:
首先,确保你已经安装了ThinkPHP框架,并且项目已经正确配置。
创建一个用户模型,用于处理用户相关的数据库操作。
namespace app\model;
use think\Model;
class User extends Model
{
// 表名
protected $table = 'users';
// 用户名字段
protected $usernameField = 'username';
// 密码字段
protected $passwordField = 'password';
}
创建一个控制器来处理用户认证和授权的逻辑。
namespace app\controller;
use think\Controller;
use app\model\User;
use think\Request;
use think\facade\Session;
use think\facade\Cache;
class AuthController extends Controller
{
// 登录接口
public function login(Request $request)
{
$username = $request->param('username');
$password = $request->param('password');
$user = User::where('username', $username)->find();
if ($user && password_verify($password, $user->password)) {
// 生成token
$token = md5(uniqid(mt_rand(), true));
Session::set('token', $token);
Cache::set($token, $user->id, 3600); // 缓存1小时
return json(['message' => '登录成功', 'token' => $token]);
} else {
return json(['message' => '用户名或密码错误'], 401);
}
}
// 注销接口
public function logout()
{
Session::delete('token');
Cache::delete(Session::get('token'));
return json(['message' => '注销成功']);
}
// 中间件验证token
protected function checkToken()
{
$token = Session::get('token');
if (!$token || !Cache::has($token)) {
return json(['message' => '未授权访问'], 401);
}
}
// 需要认证的接口示例
public function protectedAction()
{
$this->checkToken();
// 执行需要认证的操作
return json(['message' => '受保护的资源']);
}
}
创建一个中间件来验证用户的token。
namespace app\middleware;
use think\Request;
use think\Response;
class AuthMiddleware
{
public function handle(Request $request, \Closure $next)
{
$token = $request->header('Authorization');
if (!$token || !Cache::has($token)) {
return Response::create(json_encode(['message' => '未授权访问']), 'json', 401);
}
$userId = Cache::get($token);
$request->session()->set('user_id', $userId);
return $next($request);
}
}
在route
目录下的route.php
文件中配置路由。
use think\Route;
use app\controller\AuthController;
Route::post('login', 'AuthController@login');
Route::post('logout', 'AuthController@logout');
Route::group('protected', function () {
Route::get('action', 'AuthController@protectedAction')->middleware('auth');
});
在config/middleware.php
文件中注册中间件。
return [
\app\middleware\AuthMiddleware::class,
];
现在你可以测试登录、注销和受保护的接口了。
/login
,带上username
和password
参数。/logout
。/protected/action
,带上Authorization
头,值为登录时生成的token。通过以上步骤,你就可以在ThinkPHP中实现用户认证与授权了。