简体   繁体   English

如何使用瘦会话中间件在瘦休息框架中登录和退出用户?

[英]How to log user in and out in slim rest framework using slim session middleware?

I am using Slim framework to build a REST API and this is a rough application that I am using for development purposes.我正在使用 Slim 框架来构建 REST API,这是我用于开发目的的粗略应用程序。 I want to log user in and out , and I set the session variable to the user id.我想登录和注销用户,并将会话变量设置为用户 ID。 The user is able to login perfectly fine in rest API but the remote device doesnt recognize the session (which means my $SESSION['id'] is empty) where as I clearly started this session in my host rest service.用户可以在 rest API 中完美登录,但远程设备无法识别会话(这意味着我的 $SESSION['id'] 为空),因为我清楚地在我的主机休息服务中启动了这个会话。 Here is my code:这是我的代码:

require 'lib/Slim/Slim.php';
use lib\Slim\Middleware\SessionCookie;

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim(
    array(
'cookies.encrypt' => true,
    'cookies.secret_key' => 'my_secret_key',
    'cookies.cipher' => MCRYPT_RIJNDAEL_256,
    'cookies.cipher_mode' => MCRYPT_MODE_CBC
        )
);

$app->add(new \Slim\Middleware\SessionCookie(array(
    'expires' => '20 minutes',
    'path' => '/',
    'domain' => '',
    'secure' => false,
    'httponly' => false,
    'name' => 'slim_session',
    'secret' => '',
    'cipher' => MCRYPT_RIJNDAEL_256,
    'cipher_mode' => MCRYPT_MODE_CBC
)));

$app->get("/login/:string", function($string) use ($app)
        {
            $input = json_decode($string);
            try 
            {
                if ($input->username && $input->password) 
                    {
                        $user = Model::factory('Users')->where("username",$input->username)->where("password",md5($input->password))->find_one();
                        //$app->setCookie('user_id',$user->id);
                            session_cache_limiter(false);
                            session_start();
                       $_SESSION['id'] =  $user->id;

                        $status = 'success';
                        $message = 'Logged in successfully.';
                    } 
                else
                        {
                            $status = false;
                            $message = 'Could not log you in. Please try again.';
                        }

            }
            catch (Exception $e) 
                    {
                        $status = 'danger';
                        $message = $e->getMessage();
                    }
            $response = array(
                'status' => $status,
                'message' => $message
            );
            $app->response()->header("Content-Type", "application/json");
            echo json_encode($response);

        });



        $app->get("/logout",function() use ($app)
        {


            try {
                        unset($_SESSION['id']);
                        session_destroy();
                        session_start();

                        //$app->getCookie('user_id');

                        $status = 'success';
                        $message = 'You have been logged out successfully';
                    } 

            catch (Exception $e) 
                    {
                        $status = 'danger';
                        $message = $e->getMessage();
                    }
            $response = array(
                'status' => $status,
                'message' => $message
            );

            $app->response()->header("Content-Type", "application/json");
            echo json_encode($response);

        });

It is returning 'Logged in successfully' but isn't actually logging me in so in my application when I check isset($_SESSION['id']) , there is nothing in the variable.它返回“登录成功”,但实际上并没有让我登录,所以当我检查isset($_SESSION['id']) ,在我的应用程序中,变量中没有任何内容。 Does anyone know whats going on?有谁知道这是怎么回事? I am really confused because according to the slim documentation , it says :我真的很困惑,因为根据纤薄的文档,它说:

The session cookie middleware will work seamlessly with the $_SESSION superglobal so you can easily migrate to this session storage middleware with zero changes to your application code.会话 cookie 中间件将与 $_SESSION 超全局变量无缝协作,因此您可以轻松迁移到此会话存储中间件,而无需对应用程序代码进行零更改。

If you use the session cookie middleware, you DO NOT need to start a native PHP session.如果您使用会话 cookie 中间件,则不需要启动本机 PHP 会话。 The $_SESSION superglobal will still be available, and it will be persisted into an HTTP cookie via the middleware layer rather than with PHP's native session management. $_SESSION 超全局变量仍然可用,它将通过中间件层而不是 PHP 的本机会话管理持久化到 HTTP cookie 中。

The issue would seem to be that you are not starting your session soon enough not anything with session middleware I would place session_start() at the top of the index问题似乎是你没有足够快地开始你的会话而不是会话中间件我会把session_start()放在索引的顶部

require 'lib/Slim/Slim.php';
use lib\Slim\Middleware\SessionCookie;
session_start();

Now it is started every time your application routes.现在,每次您的应用程序路由时它都会启动。 So in login and logout remove your session_start() calls.所以在登录和注销时删除你的session_start()调用。 Now in logout route redirect to your landing page or somewhere like:现在在注销路由重定向到您的登录页面或类似的地方:

$app->redirect('/yourawesomepage');

that recalls session_start() so you can remove that from here your logout route.回忆session_start()这样你就可以从这里删除你的注销路由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM