1

CakePHP 2.x を使用して、Auth コンポーネントによってアクセスが拒否されたページを取得するにはどうすればよいですか? referer() 関数を使用すると、拒否されたアクションにリンクされたページが表示されます。これが私のコードです:

public function login() {
    //get the current url of the login page (or current controller+action)
    $currentLoginUrl = "/login";

    if ($this->request->is('post')) {

        $this->User->recursive = -1;            
        $user = $this->User->find(
            'first', 
            array(
                'conditions' => array(
                    'User.username' => $this->request->data['User']['username'], 
                    'User.password' => AuthComponent::password($this->request->data['User']['password'])
                )
            )
        );

        if ($user && $this->Auth->login($user['User'])) {                   
            //if the referer page is not from login page, 
            if( $this->referer() != $currentLoginUrl  )                 
            //use $this->referer() right away
            $this->redirect($this->referer('/admin', true));  //if referer can't be read, or if its not from local server, use $this->Auth->rediret() instead                   
            else
            //if the user lands on login page first, rely on our session 
            $this->redirect( $this->Session->read('beforeLogin_referer') );
        }
        else 
            $this->Session->setFlash('Username or password is incorrect', 'default', array('class' => 'alert-danger'));         
    }

    if( $this->referer() != $currentLoginUrl  )             
    //store this value to use once user is succussfully logged in
    $this->Session->write('beforeLogin_referer', $this->referer('/admin', true) ) ;  //if referer can't be read, or if its not from local server, use $this->Auth->rediret() instead                
}

したがって、基本的に何が起こるかは、私がログインしていないことです。私はこの URL にいます:

'http://localhost/hotelguide/hotels/view/17/'

リンクをクリックして

'http://localhost/hotelguide/hotels/review/17/'

ただし、それにはユーザーがログインする必要があるため、ログイン ページにリダイレクトされます。このページで referrer() をデバッグすると、次のようになります。

'http://localhost/hotelguide/hotels/view/17/'

私は何を間違っていますか?

4

2 に答える 2

2

CakePHP で Auth コンポーネントを使用して、制限されたサイトにアクセスしようとすると、ログイン ページにリダイレクトされ、参照ページがセッションに保存されます。セッション キーAuth.redirectは、探している値 (アクセスしようとしていたページ) を保持します。

AuthComponentの__unauthenticated()メソッドを見てください。セッション値をAuth.redirectに書き込むコードが含まれています。AuthComponent を使用したくない場合は、コンポーネントでの実装方法を確認し、前述の方法に基づいて独自のソリューションを作成できます。

于 2013-10-04T17:53:24.693 に答える
2

$this->referer() は正しいリファラー URL を提供しません。リファラー URL を取得したい場合は、 $this->Session->read('Auth.redirect'); を使用してください。

$this->Session->read('Auth.redirect'); で探している正確な URL を見つけることができます。

$this->referer() の値は、ページをリロードするたびに更新されます。

于 2013-10-09T09:04:20.440 に答える