LoginSignup
1
0

More than 5 years have passed since last update.

Xdomain PHPサーバーで条件チェック型のBasic認証を行う方法

Last updated at Posted at 2018-02-28

Xdomain PHPサーバーで条件チェック型のBasic認証を行う方法

Xdomainでは、管理パネルGUIから操作できるBasic認証機能が提供されています。しかしながら、これはディレクトリ単位の認証のみとなっており、「こうこうこういう条件のときだけ同一のページにBasic認証をかけたりかけなかったりしたい」という時には使えません。

そんなときは、自前でBasic認証PHPを書くやり方が使えます。
PHPでお手軽ベーシック認証 (Basic認証)
ですが、Xdomain PHPサーバーはセーフモードで動作しているため、上記のようにPHP_AUTH系サーバー変数を設定できないようになっています。

そこで、代わりに$_SERVER["REMOTE_USER"](外部で認証済みのユーザー)を使用します。

やり方

.htaccessを設定する

.htaccessに以下を設定し、ルートディレクトリに置いておきます。

.htaccess
<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]
</IfModule>

Basic認証PHP関数を書く

basic_auth.php
function basic_auth(array $auth_list)
{
    $valid_passwords = $auth_list;
    $valid_users = array_keys($valid_passwords);

    $a = base64_decode(substr($_SERVER["REMOTE_USER"], 6));
    if ((strlen($a) == 0) || (strcasecmp($a, ":") == 0)) {
        header('WWW-Authenticate: Basic realm="Restricted Area"');
        http_response_code(401);
        die("認証に失敗しました");
    } else {
        list ($name, $password) = explode(':', $a);
    }

    $validated = (in_array($name, $valid_users)) && ($password == $valid_passwords[$name]);

    if (! $validated) {
        header('WWW-Authenticate: Basic realm="Restricted Area"');
        http_response_code(401);
        die("認証に失敗しました");
    }

    // 認証成功
}

やっていること

  1. REMOTE_USERに"Basic xxxxx"(xxxxxは暗号化されたid:password)が入っているので、6文字目以降をデコード
  2. 取り出したid:passwordを展開
  3. 認証

Basic認証をかけるページに関数設置

restricted_page.php
if ($condition) {
    basic_auth(array(
        "your_id" => "your_password"
    ));
}

Basic認証をかけたいページに上記を書くと、$condition = trueのときにID/Pass入力ポップアップが出ます。そこへ、上記のように書いた場合はIdにyour_id、Passにyour_passwordを入れることで認証を通せます。

restricted_page.php
if ($condition) {
    basic_auth(array(
        "your_id1" => "your_password1",
        "your_id2" => "your_password2",
        "your_id3" => "your_password3"
    ));
}

複数もいけます。

参考

PHP による HTTP 認証 コメント欄のところ

追記

よく考えたらPHP_AUTH系変数に代入する必要性がなかったので修正しました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0