【问题标题】:How to do auto authorization如何进行自动授权
【发布时间】:2020-08-30 17:56:18
【问题描述】:

我想在注册后在我的网站上进行自动授权。 (成功用户注册后立即登录)。我做什么和我拥有什么:

我有auth.php

<?php

session_start();

function getRandom16IV()  {
    // get iv for encryption
    $alph = array_merge(range('A', 'Z'), range('a', 'z'));
    $result = "";
    $i = 0;
    while ($i != 16) {
        $result = $result . $alph[array_rand($alph, 1)];
        $i++;
    }
    return $result;
}

function getRandom255Key() {
    // get key from encryprion
    $numbers = range(1, 9);
    $result = "";
    $i = 0;
    while ($i != 255) {
        $result = $result . $numbers[array_rand($numbers, 1)];
        $i++;
    }
    return $result;
}
// get login or password values
$log_mail = $_POST['login_mail'];
$pwd      = $_POST['pwd'];
// get params for DB from config.php
include("config.php");
$con = mysqli_connect($db_ip, $db_login, $db_pwd , $db_name);
if (mysqli_connect_errno()){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// process inputs
$login_mail = $_POST['login_mail'];
$pwd = stripslashes($_POST['pwd']);
$pwd = mysqli_real_escape_string($con, $pwd);

// check if user exist
$query    = "SELECT login, pwd, email FROM `users`";
$result   = mysqli_query($con, $query);

// if user exist
$user_exist = false;
while($row = $result->fetch_assoc()) {
    if ($row["login"] == $login_mail or $row["email"] == $login_mail) {
        if ($row["pwd"] == $pwd) {
            $user_exist = true;
        }
    }
}


// authorize if user exist in DB
if ($user_exist == true) {
    include("config.php");
    include("get_from_db_functions.php");
    $key = getRandom255Key();
    $iv = getRandom16IV();
    
    $encrypt_result = openssl_encrypt($login_mail, $encr_method, $key, $options=0, $iv);

    $bday = getBday($login_mail);
    $age = calcAge($bday);

    setcookie("login_encr", $encrypt_result, time() + (86400 * 30 * 31 * 12), "/"); // год
    setcookie("logged_in", "true", time() + (86400 * 30 * 31 * 12), "/");
    setcookie("age", $age, time() + (86400 * 30 * 31 * 12), "/");
    
    $query    = "SELECT id FROM `users`WHERE login='$login_mail' OR email='$login_mail' LIMIT 1";
    $result   = mysqli_query($con, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        setcookie("id", $row['id'], time() + (86400 * 30 * 31 * 12), "/");
    }
    
    $query    = "UPDATE `users` SET encr_iv='$iv', encr_key='$key' WHERE login='$login_mail' OR email='$login_mail'";
    $result   = mysqli_query($con, $query);
    
    $_SESSION['auth-errors'] = array(); // no errors array
    
} else {
    // we have errors while authorization
    $_SESSION['auth-errors'] = array(
        'e1' => "Wrong login or password"
    );

}

$con->close();

header("Location: ../index.php");

?>

registration.php

// user registration... in sucessfull case I use this post request trying to authorize:
// set post fields

session_start();

header('Content-Type: charset=utf-8');

include("config.php");
include("get_from_db_functions.php");
include("user_params_operations.php");

function validateInputs() {
    
    $valid = true;
    $errorMessage = array();
    foreach ($_POST as $key => $value) {
        if (empty($_POST[$key])) {
            $valid = false;
        }
    }
    if($valid == false) {
        $errorMessage[] = "Need to fill all fields";
    }
    return;
}

$registration_result = validateInputs();
$_SESSION['registration_errors'] = $registration_result;

$con = setConnection();

$name = stripslashes($_POST['name']);
$name = mysqli_real_escape_string($con, $name);
$surname = stripslashes($_POST['surname']);
$surname = mysqli_real_escape_string($con, $surname);
$login = stripslashes($_POST['login']);
$login = mysqli_real_escape_string($con, $login);
$pwd = stripslashes($_POST['pwd']);
$pwd = mysqli_real_escape_string($con, $pwd);
$email = stripslashes($_POST['email']);
$email = mysqli_real_escape_string($con, $email);
$bday = stripslashes($_POST['date']);
$bday = mysqli_real_escape_string($con, $bday);

// check if user exist
$user_check_query = "SELECT id FROM users WHERE login='$login' OR email='$email' LIMIT 1";
$result = mysqli_query($con, $user_check_query);
$user = mysqli_fetch_assoc($result);

if ($user) {
    // if user exist return error
    if ($_SESSION['registration_errors'] == null) {
        $_SESSION['registration_errors'] = array();
    }
    if ($user['login'] === $login) {
        array_push($_SESSION['registration_errors'], "user already exist");
    } else if ($user['email'] === $email) {
        array_push($_SESSION['registration_errors'], "usere already exist");
    }
} else {
    
    $query    = "INSERT INTO `users` (name, surname, login, pwd, birthdate, email, encr_iv, encr_key) VALUES ( '$name', '$surname', '$login', '$pwd', '$bday', '$email', '', '')";
    $result   = mysqli_query($con, $query);
    
    
    $getid = "SELECT id FROM users WHERE login='$login' OR email='$email' LIMIT 1";
    $result = mysqli_query($con, $getid);
    while ($row = mysqli_fetch_assoc($result)) {
        $id = $row['id'];
        $age = calcAgeByBirthDate($bday);
        $query    = "INSERT INTO `user_params` (user_id, age, happiness_level, good_habbits, bad_habbits, max_lifespan, expected_lifespan)
                    VALUES ('$id', '$age', 0, '', '', 0, 0)";
        $res   = mysqli_query($con, $query);
    }



    // set post fields
    $post = [
        'login_mail' => $login,
        'pwd' => $pwd
    ];

    $ch = curl_init('auth.php');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

    // execute!
    $response = curl_exec($ch);

    // close the connection, release resources used
    curl_close($ch);

    // do anything you want with your response
    // var_dump($response);
}



$con->close();
header("Location: ../profile.php");

如果我单独使用身份验证文件,注册工作正常,但它没有按我的意愿授权(通过注册后的发布请求)。

我做错了什么?

【问题讨论】:

  • 您的授权流程如何运作?请edit您的问题包括“auth.php”文件的源代码。在这里使用 CURL 请求很可能不是您想要的。
  • @Progman 进行了编辑,请参阅
  • 身份验证文件看起来很糟糕:$pwd = mysqli_real_escape_string($con, $pwd); - 为什么你需要转义一个无论如何都应该被散列的密码?
  • @SJacks 我认为它可以让我避免一些脚本注入?我知道代码不好,但问题在另一个
  • 这是散列之美的一部分,您不需要像散列那样使用多种方法来清理帖子值 - 获取密码,添加胡椒,散列并与存储的散列进行比较。让事情变得更轻松、更安全。

标签: php


【解决方案1】:

在与 Encrypt 的会话中存储用户详细信息的最佳解决方案。

并使用它!

编辑更改

registration.php

// set post fields
$_SESSION['en_user'] = encrypt($login);
$_SESSION['en_pass'] = encrypt($pwd);
header("Location: auth.php");
//end

encrypt.php

function encrypt($payload) {
  $key ='whatxxxxwhatever';
  $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
  $encrypted = openssl_encrypt($payload, 'aes-256-cbc', $key, 0, $iv);
  $var = base64_encode($encrypted . '::' . $iv);
  $var = strtr($var, '+/=', '-_,');
  return $var;
}

function decrypt($garble) {
    $garble = strtr($garble, '-_,', '+/=');
    $key ='whatxxxxwhatever';
    list($encrypted_data, $iv) = explode('::', base64_decode($garble), 2);
    return openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv);
}

auth.php

//include encrypt.php
if(isset($_POST['login_mail']) && isset($_POST['pwd']))
{
    $log_mail = $_POST['login_mail'];
    $pwd      = $_POST['pwd'];
}elseif(isset($_SESSION['en_user']) && isset($_SESSION['en_pass']))
{
    $log_mail = decrypt($_SESSION['en_user']);
    $pwd      = decrypt($_SESSION['en_pass']);
}else{
    unset($_SESSION['en_user']); 
    unset($_SESSION['en_pass']); 
    exit;
}

在“数据库”中使用会话以确保安全。

试试这个

【讨论】:

    【解决方案2】:

    在这里使用 cURL 不是解决方案。 cURL 函数将对文件发出新的不同 HTTP 请求,其中客户端将不是用户的浏览器,而是正在运行的 Web 服务器 PHP。任何会话/登录 cookie 都会保存在网络服务器上,但它应该存储在用户的浏览器中。

    您必须使用include 语句从不同的 PHP 脚本加载和运行代码。它应该类似于include 'auth.php';,但执行起来“太多了”。您只需要生成和发送 cookie 的部分。根据您的代码工作方式以及您希望如何构建系统,您可以将“生成和发送登录 cookie”部分提取到单独的 PHP 脚本或新函数中。因此,您可以编写类似include 'sendauthcookie.php';sendLoginCookies($login_mail); 的内容来生成登录cookie 并将它们发送到用户的浏览器。可以从您的“auth.php”文件以及“registration.php”文件中调用此代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多