m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

herokuでCORSを確認

herokuでCORSを確認

CORS

developer.mozilla.org

要はajaxとかでホストの異なるリクエストを取得できないこと

環境

大元(リクエスト先)

mighty-taiga-69931.herokuapp.com

index.php

<?php
session_start();
if ($_SESSION["auth"] === true) {
    // redirect
    header('Location: ./top.php');
    exit;
}
?>
<!DOCTYpe html>
<html>
<head>
    <script type="text/javascript" src="./jquery-3.5.1.min.js"></script>
</head>
<body>
    <div>
    <label>
            userid: <input type="text" class="id" ame="userid" />
        </label>
        <label>
            password: <input type="password" class="pw" name="password" />
        </label>
        <button type="button" class="login-btn">
            login
        </button>
    </div>
<script>
$(function() {
    $(".login-btn").on("click", function() {
        console.log("login");

        let params = {
            "userid": $(".id").val(),
            "password": $(".pw").val()
        };

        $.ajax({
            type: "POST",
            url: "./login.php",
            contentType: 'application/json',
            dataType: "json",
            data: JSON.stringify(params),
            success: function(msg){
                console.log(msg);
                location.href = "/";
            },
            error: function(msg){
                console.log(msg);
            }
        });
    });
});
</script>
</body>
</html>

login.php

<?php
session_start();

$json = file_get_contents("php://input");
$contents = json_decode($json, true);
//var_dump($contents);

$new_sessionid = session_id();
$auth = "NG";
if ($contents["userid"] == "admin"  && $contents["password"] == "pass") {
    $auth = "OK";

    // 
    session_regenerate_id(true);
    $new_sessionid = session_id();
    $_SESSION["auth"] = true;
}

$result = [
    "status" => 200,
    "auth" => $auth,
    "session_id" => $new_sessionid,
];

echo json_encode($result);
?>

logout.php

<?php
session_start();

$_SESSION = array();

if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

session_destroy();
session_regenerate_id(true);
?>

検証用(大元へアクセスする方)

pacific-harbor-45480.herokuapp.com

index.php

<!DOCTYpe html>
<html>
<head>
    <script type="text/javascript" src="./jquery-3.5.1.min.js"></script>
</head>
<body>
    <div>
    <label>
            userid: <input type="text" class="id" ame="userid" />
        </label>
        <label>
            password: <input type="password" class="pw" name="password" />
        </label>
        <button type="button" class="login-btn">
            login
        </button>
    </div>
<script>
$(function() {
    $(".login-btn").on("click", function() {
        console.log("login");

        let params = {
            "userid": $(".id").val(),
            "password": $(".pw").val()
        };

        $.ajax({
            type: "POST",
            url: "https://mighty-taiga-69931.herokuapp.com//login.php",
            contentType: 'application/json',
            dataType: "json",
            data: JSON.stringify(params),
            success: function(msg){
                console.log(msg);
                location.href = "/";
            },
            error: function(msg){
                console.log(msg);
            }
        });
    });
});
</script>
</body>
</html>

確認

異なるホストへajaxへリクエストを送信

        $.ajax({
            type: "POST",
            url: "https://mighty-taiga-69931.herokuapp.com//login.php",
            contentType: 'application/json',
            dataType: "json",
            data: JSON.stringify(params),
            success: function(msg){
                console.log(msg);
                location.href = "/";
            },
            error: function(msg){
                console.log(msg);
            }
        });

結果

Access to XMLHttpRequest at 'https://mighty-taiga-69931.herokuapp.com//login.php' from origin 'https://pacific-harbor-45480.herokuapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

f:id:m_shige1979:20201003180610p:plain

うん、出ました。 対策としては「Access-Control-Allow-Headers」を大元より返却するようにする。

app側でやるかnginxとかのwebサーバのどちらかで対応できるかも

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,POST,HEAD,OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
e

もし、ホストを任意のもの限定にしたい場合は

header("Access-Control-Allow-Origin: https://pacific-harbor-45480.herokuapp.com");

みたいにすることで対応可能

終わり