linux

ThinkPHP如何实现用户认证与授权

小樊
37
2025-06-29 09:43:57
栏目: 编程语言

在ThinkPHP中,实现用户认证与授权可以通过以下步骤来完成:

1. 安装和配置ThinkPHP

首先,确保你已经安装了ThinkPHP框架,并且项目已经正确配置。

2. 创建用户模型

创建一个用户模型,用于处理用户相关的数据库操作。

namespace app\model;

use think\Model;

class User extends Model
{
    // 表名
    protected $table = 'users';

    // 用户名字段
    protected $usernameField = 'username';

    // 密码字段
    protected $passwordField = 'password';
}

3. 创建控制器

创建一个控制器来处理用户认证和授权的逻辑。

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' => '受保护的资源']);
    }
}

4. 创建中间件

创建一个中间件来验证用户的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);
    }
}

5. 配置路由

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');
});

6. 配置中间件

config/middleware.php文件中注册中间件。

return [
    \app\middleware\AuthMiddleware::class,
];

7. 测试

现在你可以测试登录、注销和受保护的接口了。

通过以上步骤,你就可以在ThinkPHP中实现用户认证与授权了。

0
看了该问题的人还看了