Simple, Slowly

ブログを引っ越ししました。http://48.jp

CakePHPのSSL Componentでhttpとhttpsを切り替える

SSL Componentを使うと、http→httpshttps→httpの転送をやってくれるので便利です。
SSL Component


使い方

/* app_controller.php */
var $components = array(
    'Secured.Ssl' => array(
        'secured' => array(
            'users' => 'login',
            'store' => '*',
            'post' => array('index', 'edit')
        ),
        'autoRedirect' => true,  // Set to false to temporarily disable this component
    )
 );

上の例だと

user_controllerのlogin
store_controllerの全てのaction
post_controllerのindexとedit

に対してhttpでアクセスがきた場合はhttpsに転送します。


逆に定義されていないactionにhttpsでアクセスした場合は、httpに転送となります。


autoRedirectをfalseにすると転送を無効にできます。
デフォルトはtrueなので定義しなくてもOKです。


ちなみに、getパラメーターは引き継がれません。
getパラメーターも引き継ぐようにしました。

    /** 
     * Redirects current request to be SSL secured
     *
     * @return void
     * @todo Make protocol & subdomain ('https' & 'www' configurable)
     * @todo allow conditional passing of server identifier
     */
    public function forceSSL() {
        $server = env('SERVER_NAME');
        $redirectUrl = $this->setParam("https://$server{$this->controller->here}");
        $this->controller->redirect($redirectUrl);
    }   

    /** 
     * Symmetric method to forceSSL, which redirects the current
     * executing request to non-SSL.
     *
     * @return void
     * @todo Make protocol & subdomain ('https' & 'www' configurable)
     * @todo allow conditional passing of server identifier
     */
    public function forceNoSSL() {
        $server = env('SERVER_NAME');
        $redirectUrl = $this->setParam("http://$server{$this->controller->here}");
        $this->controller->redirect($redirectUrl);
    }   

    /** 
     * URLの引数を &key=val の形式で返す。引数が存在しない場合は、空の文字列を返す。
     * @return string
     */
    private function getParam() {
        $paramList = array();
        $paramStr = ''; 
            
        foreach ($this->controller->params['url'] as $key => $params) {
            if($key !== 'url') {
                $paramList[$key] = $params;
            }   
        }   
        foreach ($paramList as $key => $val) {
            $paramStr .= "&{$key}={$val}"; 
        }
        return $paramStr;
    }

    /**
     * get parameter is set. 
     * @param string $redirectUrl
     * @return string redirect url
     */
    private function setParam($redirectUrl) {
        $paramStr = $this->getParam();
        if (!empty($paramStr)) {
            $redirectUrl .= "?{$paramStr}";
        }
        return $redirectUrl;
    }


httpsで注意してほしいことのまとめ。
httpsでの注意点