duanchigeng4313 2014-07-29 05:22
浏览 55
已采纳

cakephp ajax请求中的Cookie问题?

I am implementing Ajax login using auth component in my cakephp app. Everything is working fine except remember me.

I am trying to set cookie using Cookie component but seems it's not sending cookie with response.

I have tried other setting domain, path and user agent check false in session variable but it didn't work.

If I use setcookie method then it's sending cookie in response (but I need cakephp cookie as I am saving array in cookie)

Below is code that I am using:

public function beforeFilter() {
    parent::beforeFilter();

    $this->Cookie->path = '/';
    $this->Cookie->httpOnly = true;


    if (!$this->Auth->loggedIn() && $this->Cookie->read('rememberMe')) {

        $cookie = $this->Cookie->read('rememberMe');

        $user = $this->User->find('first', array(
            'conditions' => array(
                'User.username' => $cookie['username'],
                'User.password' => $cookie['password']
            )
        ));

        if ($user && !$this->Auth->login($user['User'])) {
            $this->redirect(array('action' => 'logout')); // destroy session &   cookie
        } else {
            $this->redirect($this->Auth->redirectUrl()); // redirect to Auth.redirect if it is set, else to Auth.loginRedirect ('/users/userhome') if it is set, else to /
        }
    }
}

Here is login function code:

if ($this->Auth->login()) {
    Croogo::dispatchEvent('Controller.Users.loginSuccessful', $this);
    if ($this->request->data['User']['remember_me'] == 1) {
        $cookieTime = "2 months"; // You can do e.g: 1 week, 17 weeks, 14 days
        // remove "remember me checkbox"
        unset($this->request->data['User']['remember_me']);
        // hash the user's password
        $this->request->data['User']['password'] = $this->Auth->password($this->request->data['User']['password']);
        // write the cookie
        $this->Cookie->write('rememberMe', $this->request->data['User'], true, $cookieTime);

    }
    $response['status'] = 'success';
    $response['redirect_url'] = Router::url(array('action' => 'dashboard'), true);
    $response['action'] = 'login';
    $response['message'] = __d('sharbook', 'You have logged in successfully. Please stand by...');
    echo json_encode($response);
}

Please help me to fix issue.

  • 写回答

1条回答 默认 最新

  • doujuanju3076 2014-07-29 09:40
    关注

    First thing, you should enabled debug mode in your application (Configure::write('debug', 2)), or check the debug logs, then you'd see that you are getting a "Cannot modify header information - headers already sent" warning.

    Do not manually output data using echo or the like

    Except for session cookies which are being sent immediately when a session is started, normal cookies are queued in the CakeResponse object ($this->response in your controller) until after the controller action has been executed, so doing an echo in your controller action will cause headers and data to be sent, and therefore the cookie headers cannot be sent anymore.

    Use a view or the CakeResponse object instead

    Simple fix, either use the JSON view functionality (recommended)

    class YourController extends AppController {
        public $components = array('RequestHandler');
    
        // ...
    
        public function login() {
            // ...
    
            if ($this->Auth->login()) {
                // ...
    
                $response['status'] = 'success';
                $response['redirect_url'] = Router::url(array('action' => 'dashboard'), true);
                $response['action'] = 'login';
                $response['message'] = __d('sharbook', 'You have logged in successfully. Please stand by...');
    
                $this->set('response', $response);
                $this->set('_serialize', array('response'));
            }
        }
    }
    

    or properly set the response body on the response object

    $this->response->body(json_encode($response));
    $this->response->type('json');
    

    so that the data is being sent by CakeResponse::send() (which will properly send the cookie headers first) after the action has been dispatched.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 电脑拓展屏桌面被莫名遮挡
  • ¥20 ensp,用局域网解决
  • ¥15 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复
  • ¥15 matlab透明图叠加
  • ¥50 基于stm32l4系列 使用blunrg-ms的ble gatt 创建 hid 服务失败
  • ¥150 计算DC/DC变换器平均模型中的参数mu
  • ¥25 C语言代码,大家帮帮我
  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)