I'm having trouble creating a Custom Authentication! I'm using a free host from 000WebHost to test Photon's multiplayer on Unity, but I get the following error in Unity debug:
OperationResponse 230: ReturnCode: 32755 (Custom authentication deserialization failed: Unexpected character encountered while parsing value: U. Path '', line 0, position 0.).
Parameters: {} Server: NameServer Address: ns.exitgames.com:5058
UnityEngine.Debug:LogError(Object)
Photon.Realtime.LoadBalancingClient:DebugReturn(DebugLevel, String) (at Assets/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:1835)
Photon.Realtime.LoadBalancingClient:OnOperationResponse(OperationResponse) (at Assets/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:1909)
ExitGames.Client.Photon.PeerBase:DeserializeMessageAndCallback(StreamBuffer) (at C:/Dev/photon-sdk-dotnet/PhotonDotnet/PeerBase.cs:616)
ExitGames.Client.Photon.EnetPeer:DispatchIncomingCommands() (at C:/Dev/photon-sdk-dotnet/PhotonDotnet/EnetPeer.cs:545)
ExitGames.Client.Photon.PhotonPeer:DispatchIncomingCommands() (at C:/Dev/photon-sdk-dotnet/PhotonDotnet/PhotonPeer.cs:1473)
Photon.Pun.PhotonHandler:FixedUpdate() (at Assets/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:130)
My Unity authentication code:
using Photon.Pun;
using Photon;
public class Login : MonoBehaviour {
public InputField User_Input;
public InputField Pass_Input;
public Text Error_Text;
public string username;
public string password;
public void UserName(){
username = User_Input.text.ToString ();
}
public void UserPass(){
password = Pass_Input.text.ToString ();
}
public void SubmitLogin(){
PhotonNetwork.AuthValues = new AuthenticationValues ();
PhotonNetwork.AuthValues.AuthType = CustomAuthenticationType.Custom;
PhotonNetwork.AuthValues.AddAuthParameter ("username", username);
PhotonNetwork.AuthValues.AddAuthParameter ("password", password);
PhotonNetwork.ConnectUsingSettings();
}
void OnJoinedLooby(){
Debug.Log ("We did it");
}
void OnGUI(){
GUILayout.Label (PhotonNetwork.connectionStateDetailed.ToString ());
}
}
My server-side code:
<?php
include "db.php";
$username = $_GET['username'];
$password = $_GET['password'];
$check = mysqli_query($conn , "SELECT * FROM accounts WHERE `username`='".$username."'");
$numrows = mysqli_num_rows($check);
if ($numrows == 0){
die ("Username does not exist.");
}else{
$password = md5($password);
while($row = mysqli_fetch_assoc($check)){
if ($password == $row['password']){
$login_info = array(
"ResultCode" => 1,
"Message" => "You are connected!");
}else{
$login_info = array(
"ResultCode" => 2,
"Message" => "Wrong username or password");
}
}
}
$json = json_encode($login_info);
echo $json;
?>
In the photon panel I placed Url mydomain/auth.php and I did not put any optional Key/Value Pairs
I do not know what the problem is, if anyone knows
I replied on our forum. Posting the same here:
The letter "U" is a hint that it could be from "Username does not exist.".
Replace
die ("Username does not exist.");
with
$login_info = array(
"ResultCode" => 3,
"Message" => "Username does not exist."
);
If the issue persists, use postman and send an HTTP request with proper query string values to your server and see what it returns. Fix that.
Related
Here's my code generating the token:
public static function GenerateNewAuthTokens(User $user): string {
$issuedAt = new DateTimeImmutable();
$expire = $issuedAt->modify('+' . AuthenticationHelper::AUTH_EXPIRE_MINUTES . ' minutes');
$username = $user->Username;
$issuedAtTimestamp = $issuedAt->getTimestamp();
$auth_data = [
'iat' => $issuedAtTimestamp, // Issued at: time when the token was generated
'iss' => AuthenticationHelper::SERVER_NAME, // Issuer
'nbf' => $issuedAtTimestamp, // Not before
'exp' => $expire->getTimestamp(), // Expire
'userName' => $username, // User name
];
return JWT::encode(
$auth_data,
AuthenticationHelper::SECRET_KEY,
AuthenticationHelper::ALGORITHM
);
}
Here is my code attempting to decode the token:
public static function GetAuthData(): ?object {
$headers = getallheaders();
if (isset($headers) && count($headers) && isset($headers['Authorization']) && strlen($headers['Authorization']) > 7) {
try {
$token = explode(" ", $headers['Authorization'])[1];
$decodedToken = JWT::decode($token, new Key(AuthenticationHelper::SECRET_KEY, AuthenticationHelper::ALGORITHM));
return $decodedToken;
} catch (\Throwable $th) {
//TODO
$err = $th;
}
}
return null;
}
It throws the "Signature verification failed" error in the JWT code here.
So far as I can tell - I'm following the example given on the repo home screen to a reasonable approximation.
I am using HS512 but have tried HS256 as well with no difference.
I have confirmed that the token I'm attempting to decode is exactly what was generated in the first method.
It's failing the compare check here, due to $hash and $signature not matching.
So turns out I wasn't sending the exact same token back that I was receiving. When JWT encodes the token data, it trims off the = at the end of any of the base64 encoded strings.
What I had stored contains those = at the end (usually). Because of this, when it ran its compare - it failed.
In summary - dur - check the values better.
I'm trying verify online payment.
After I connect to bank getway by using function actionToken and pay, bank send me some information to verify payment with POST method, but I can't receive the information with POST method.
Here is my payment controller, function actionToken is for send data from my website such as amount ,and function actionVerify is for verifying payment that I have receive bank information. Here is my problem, that I don't know what do I have to do.
<?php
namespace frontend\controllers;
use Yii;
use common\models\Order;
class PaymentController extends \yii\web\Controller {
public function actionRequest() {
include_once('lib/nusoap.php');
$terminalId = "xxxx"; // Terminal ID
$userName = "xxxx"; // Username
$userPassword = "xxxxxxx"; // Password
$orderId = time(); // Order ID
$amount = $amount.'0'; // Price / Rial
$localDate = date('Ymd'); // Date
$localTime = date('Gis'); // Time
$additionalData = $model['notes'];
$callBackUrl = "http://dastsazkala.com/payment/verify?id=".$id; // Callback URL
$payerId = $id;
$parameters = [
'terminalId' => $terminalId,
'userName' => $userName,
'userPassword' => $userPassword,
'orderId' => $orderId,
'amount' => $amount,
'localDate' => $localDate,
'localTime' => $localTime,
'additionalData' => $additionalData,
'callBackUrl' => $callBackUrl,
'payerId' => $payerId];
$client = new \nusoap_client('https://bpm.shaparak.ir/pgwchannel/services/pgw?wsdl');
$namespace='http://interfaces.core.sw.bps.com/';
$result = $client->call('bpPayRequest', $parameters, $namespace);
}
public function actionVerify($id = null, $check = null) {
//my promblem is in this function, that I cant receive posts.
if ($_POST['ResCode'] == '0') {
//payment is correct
include_once('lib/nusoap.php');
$client = new nusoap_client('https://bpm.shaparak.ir/pgwchannel/services/pgw?wsdl');
$namespace='http://interfaces.core.sw.bps.com/';
$terminalId = "xxxx"; // Terminal ID
$userName = "xxxxx"; // Username
$userPassword = "xxxxx"; // Password
$orderId = $_POST['SaleOrderId']; // Order ID
$verifySaleOrderId = $_POST['SaleOrderId'];
$verifySaleReferenceId = $_POST['SaleReferenceId'];
$parameters = [
'terminalId' => $terminalId,
'userName' => $userName,
'userPassword' => $userPassword,
'orderId' => $orderId,
'saleOrderId' => $verifySaleOrderId,
'saleReferenceId' => $verifySaleReferenceId];
// Call the SOAP method
$result = $client->call('bpVerifyRequest', $parameters, $namespace);
if($result == 0) {
//verify is correct
echo 'The transaction was successful';
} else {
//error in pyament
}
} else {
//error in pyament
}
}
}
In this function I receive nothing.
Do I have to do something in behavior of my controller or something else?
Why I can't receive any posts in my controller?
General chrome:
Request URL: http://dastsazkala.com/payment/verify
Request Method: POST
Status Code: 301 Moved Permanently
Remote Address: 138.201.30.123:80
Referrer Policy: no-referrer-when-downgrade
Here what I receive:
The problem was this: my website url has www in the beginning, but there was no www in callBackUrl.
So I changed
$callBackUrl = "http://www.dastsazkala.com/payment/verify?id=".$id; //add www. in the beginning
instead of
$callBackUrl = "http://dastsazkala.com/payment/verify?id=".$id;
and I can receive Form Data with POST method from bank getway.
dastsazkala.com/payment/verify Redirects to www.dastsazkala.com/payment/verify notice the www!
the query result:
Status Code: 301 Moved Permanently
clearly hints that there might be a redirection going on
i am a beginner in PHP & MySQL development, I am following a tutorial. I am trying to make login system, after inserting data to Mysql in registration. I want to validate the password from the database and the password from user in login page, if it is match, then login is successful.
here is the password from the database, as we can see, for username=admin the password is 3462623.....
The data type of this database is like this
as we can see, the data type for password and salt is Binary.
when I tried to var_dump the variable which stores the value from the database, the password and salt is different from what appears in the database.
the password should be : 3462623.....
but from var_dump, the password is : 4bb5d8229634bf5 .....
other data like id,username,email are correct. just password and salt are different.
I suspect this is because the return value data type from var_dump is String, but when i stored to database, the datatype is Binary, how do I fix that ? it seems that from tutorial I saw, the login system still OK even though the password in string data type.
to be honest I don't understand why it has to be Binary data type. but I guess it because it will be encrypted.
so what went wrong in here?
here is the code :
Registration Process
$username = htmlentities($_REQUEST["username"]);
$password = htmlentities($_REQUEST["password"]);
$fullname = htmlentities($_REQUEST["fullname"]);
$email = htmlentities($_REQUEST["email"]);
if (empty($username) || empty($password) || empty($fullname) || empty($email)) {
$returnArray = [
"status" => "400",
"message" => "missing required information"
];
echo json_encode($returnArray);
return;
}
//encrypt the password
$salt=openssl_random_pseudo_bytes(20);
$securedPassword = sha1($password.$salt);
// Create Connection
$file = parse_ini_file("../../../twitter.ini");
$dbhost = trim($file["host"]);
$dbusername = trim($file["username"]);
$dbpassword = trim($file["password"]);
$dbname = trim($file["dbname"]);
$access = new access($dbhost,$dbusername,$dbpassword,$dbname);
$access->connect();
function registerUser($username,$password,$salt,$email,$fullname) {
$query = "INSERT INTO users SET username=?, password=?,salt=?,email=?,fullname=?";
$statement = $this->conn->prepare($query);
if (!$statement) {
throw new Exception($statement->error);
}
$statement-> bind_param('sssss',$username,$password,$salt,$email,$fullname);
$returnValue = $statement -> execute();
return $returnValue;
}
// Insert data to database
$result = $access->registerUser($username,$securedPassword,$salt,$email,$fullname);
if ($result) {
// get data from database
$user = $access->selectUser($username);
$resultArray = [
"status" => "200",
"message" => "Sucessfully registered",
"id" => $user["id"],
"username" => $user["username"],
"email" => $user["email"],
"avatar" => $user["avatar"],
"fullname" => $user["fullname"]
];
login process
$username = htmlentities($_REQUEST["username"]);
$password = htmlentities($_REQUEST["password"]);
if (empty($username) || empty($password)) {
$returnArray = [
"status" => "400",
"message" => "missing required information"
];
echo json_encode($returnArray);
return;
}
// make connection
$file = parse_ini_file("../../../twitter.ini");
$dbhost = trim($file["host"]);
$dbusername = trim($file["username"]);
$dbpassword = trim($file["password"]);
$dbname = trim($file["dbname"]);
$access = new access($dbhost,$dbusername,$dbpassword,$dbname);
$access->connect();
$user = $access -> getUserData($username);
if (empty($user)) {
$returnArray = [
"status" => "403",
"message" => "User is not found"
];
echo json_encode($returnArray);
return;
} else {
// password validation
$securedPassword = $user["password"];
$salt = $user["salt"];
if ($securedPassword === sha1($password.$salt)) {
$resultArray = [
"status" => "200",
"message" => "Login Success!",
"id" => $user["id"],
"username" => $user["username"],
"email" => $user["email"],
"avatar" => $user["avatar"],
"fullname" => $user["fullname"]
];
} else {
$returnArray = [
"status" => "403",
"message" => "Password didn't match"
];
}
}
$access ->disconnect();
echo json_encode($returnArray);
As pointed out by other users, password and salt should be char or varchar or even text, but not binary.
The reason you see a difference between them is based on the method of access and character sets used in retrieval and display.
In one case you are retrieving using PHP and then displaying using (likely) a PRE tag and showing it on a web page. In the other case you are viewing it in phpMyAdmin or some other MySQL desk system. Each one of these requires several translations before viewing and as binary data they will not display the same way reliably when retrieved with two different pathways (phpMyAdmin will translate the character set differently, and then display the result differently).
A simple solution to this is to switch to a non-binary (TEXT/VARCHAR) field definition.
Alternately, you could attempt to retrieve them as HEX or some other Binary Friendly display method in both your MySQL desk (using a query, not just displaying in the table) and in the php/mysqli query as well. In essence, then, you'd be converting the binary to a known text display set.
I have built a log in system and I am adding google recaptcha for security. I am getting an error on this line: $result = json_decode($url, TRUE);
The error says;
failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request.
This is my first time using recaptcha and I am not sure if this is a common mistake.
<?php
$secret = '*****';
$response = $_POST['g-recaptcha-response'];
$remoteip = $_SERVER['REMOTE_ADDR'];
$captcha = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip");
$result = json_decode($url, TRUE);
$username;
$password;
$captcha;
if (isset($_POST['username']))
$username = $_POST['username'];
if (isset($_POST['password']))
$password = $_POST['password'];
if (isset($_POST['g-recaptcha-response']))
$captcha = $_POST['g-recaptcha-response'];
if (!$captcha) {
echo '<p class="error-message">Please Complete The Captcha!</p>';
header("location: login.php");
exit;
}
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LfG-S8UAAAAAIqW1sBE31yMPyO4zeqOCgDzL1mA&response=" . $captcha . "&remote=" . $_SERVER['REMOTE_ADDR']), true);
if ($response['success'] == false) {
echo '<p class="error-message">Please Fill Captcha!</p>';
} else {
echo '<p class="error-message2">Welcome</p>';
}
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$q = $handler->prepare('SELECT * FROM users WHERE username = ?');
$q->execute(array($username));
$result = $q->fetch(PDO::FETCH_ASSOC);
if ($result !== false) {
$hash_pwd = $result['password'];
$hash = password_verify($password, $hash_pwd);
if ($hash) {
$_SESSION['username'] = $username;
header("location:index.php");
return;
} else {
echo '<p class="error-message3"><br><br>You have ented an incorrect login!<br>Please try again</p>';
}
}
}
?>
If this really is your complete code:
It seems you are using $url (in the line $result = ...) without having initialized it before.
Additionally, I would expect that a variable with name $url contains an URL, and URLs are not in JSON format, so this raises some alarm signs. You eventually do not want to JSON-parse an URL, but instead parse what this URL returns when calling it.
Secondly, sometimes the line numbers within error messages or warnings are misleading. I highly doubt that the error you have mentioned (HTTP request failed) is related to json_decode(). json_decode(), as the name implies, just parses a string in JSON format, but does not load anything via HTTP.
So the error message probably comes from the line above ($captcha = file_get_contents(...);). I suppose that the URL you give there is wrong, or that Google refuses the request for another reason.
The first thing I would do is putting that URL into a variable and print it out (e.g. by using error_log()).
If that does not lead to the source of the problem, I would copy that URL (not from the code, but from the output produced by error_log()) and paste it directly into the address bar of a new browser window. If this yields the expected result (you should see Google's answer to the request in the browser window), the error is in your code. Otherwise, the error is in the URL.
<?php
session_start();
error_reporting(E_ALL);
try {
$ini = parse_ini_file("/var/www/admin.ini");
$user = $ini['user'];
$pass = $ini['pass'];
$name = $ini['name'];
$host = $ini['host'];
$handler = new PDO('mysql:host='.$host.'; dbname='.$name, $user, $pass);
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
error_log($e);
echo $e->getMessage();
}
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => [
'secret' => '********',
'response' => $_POST['g-recaptcha-response'],
],
]);
$response = json_decode(curl_exec($curl));
if (!$response->success) {
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$q = $handler->prepare('SELECT * FROM users WHERE username = ?');
$q->execute(array($username));
$result = $q -> fetch(PDO::FETCH_ASSOC);
if ($result !== false) {
$hash_pwd = $result['password'];
$hash = password_verify($password, $hash_pwd);
if ($hash) {
$_SESSION['username'] = $username;
header("location:index.php");return;
}
else {echo '<p class="error-message3"><br><br>You have ented an incorrect login!<br>Please try again</p>';
}
}
}
}
?>
I'm trying to authenticate on Bing Ads Api but I'm getting this message:
Authentication failed. Either supplied credentials are invalid or the account is inactive
This is my code:
$UserName = "xxx#hotmail.com";
$Password = "xxx";
$DeveloperToken = "xxx";
$CustomerId = xxx;
$AccountId = xxx;
$wsdl = "https://campaign.api.bingads.microsoft.com/Api/Advertiser/CampaignManagement/V10/CampaignManagementService.svc?singleWsdl";
try
{
$proxy = ClientProxy::ConstructWithAccountAndCustomerId($wsdl, $UserName, $Password, $DeveloperToken, $AccountId, $CustomerId, null);
// Specify one or more campaigns.
$campaigns = array();
$campaign = new Campaign();
$campaign->Name = "Winter Clothing " . $_SERVER['REQUEST_TIME'];
$campaign->Description = "Winter clothing line.";
$campaign->BudgetType = BudgetLimitType::MonthlyBudgetSpendUntilDepleted;
$campaign->MonthlyBudget = 1000.00;
$campaign->TimeZone = "PacificTimeUSCanadaTijuana";
$campaign->DaylightSaving = true;
// Used with FinalUrls shown in the ads that we will add below.
$campaign->TrackingUrlTemplate =
"http://tracker.example.com/?season={_season}&promocode={_promocode}&u={lpurl}";
$campaigns[] = $campaign;
// Add the campaign, ad group, keywords, and ads
$campaignIds = AddCampaigns($proxy, $AccountId, $campaigns);
PrintCampaignIdentifiers($campaignIds);
}
catch (SoapFault $e)
{
// Output the last request/response.
print "\nLast SOAP request/response:\n";
print $proxy->GetWsdl() . "\n";
print $proxy->GetService()->__getLastRequest()."\n";
print $proxy->GetService()->__getLastResponse()."\n";
// Campaign Management service operations can throw AdApiFaultDetail.
if (isset($e->detail->AdApiFaultDetail))
{
// Log this fault.
print "The operation failed with the following faults:\n";
$errors = is_array($e->detail->AdApiFaultDetail->Errors->AdApiError)
? $e->detail->AdApiFaultDetail->Errors->AdApiError
: array('AdApiError' => $e->detail->AdApiFaultDetail->Errors->AdApiError);
// If the AdApiError array is not null, the following are examples of error codes that may be found.
foreach ($errors as $error)
{
print "AdApiError\n";
printf("Code: %d\nError Code: %s\nMessage: %s\n", $error->Code, $error->ErrorCode, $error->Message);
switch ($error->Code)
{
case 105: // InvalidCredentials
break;
case 117: // CallRateExceeded
break;
default:
print "Please see MSDN documentation for more details about the error code output above.\n";
break;
}
}
Sorry for the delayed reply. I noticed that you are setting the UserName to ***#hotmail.com. If you are using an email address login i.e. Microsoft account, then you must use OAuth i.e. set the AuthenticationToken header element instead of setting the UserName/Password fields.