How to implement authentication on a REST architecture with Parse - php

I am currently redoing a legacy web application that uses the PHP Parse SDK, and I am in the login authentication part. In the old application, we used $ _SESSION and ParseToken when doing ParseUser::signIn() and ParseUser::currentUser() to check if you have a session with a valid token, however the new application is being made using the REST architecture, where one of the REST concepts is that the server must not keep state, that is, be stateless, and in that case it would be the client that would have to send the necessary data.
When searching the internet and forums, I saw that it is common for developers to authenticate with JWT, where the client would make a request for a server's route and the server would return a token, and through that token authentication would take place.
I even implemented something using Firebase / jwt-php, where the client [Postman] makes a request for the route /login sending via body [username, password] and in case of success, returns the token to be used in secure route requests.
NOTE: Code is as simple as possible, without validation and cleaning just to show the example.
Action /login
$username = $request->getParsedBody()['username'];
$password = $request->getParsedBody()['password'];
$userAuthenticated = ParseUser::logIn($username, $password);
$payload = [
'data' => $userAuthenticated,
'exp' => time() + 3600
];
$token = JWT::encode($payload, $_ENV['JWT_SECRET_KEY']);
echo json_encode(['token' => $token]);
And the protected routes have a middleware that checks if the time has expired, and if this has happened, an exception with a 401 code is launched.
So far so good, authentication works, the problem I don't know if it's right to do it this way, since I need to give a ParseUser::logIn(), just to generate a session in the database and I don't even use it this session to do some authentication, with the exception of operations in the bank, because from what I saw in the documentation, if there is no valid session in the database, the application will return invalid session token error and also when making the request for another route ParseUser::currentUser() returns null, and this may be a problem in the future.
Does anyone have any idea how I can implement authentication for a REST application made in PHP? I appreciate the help !!

I believe the easiest way would be just replacing the default session storage (which uses $_SESSION) to something else that stores the session in, for example, Redis. Reference: https://docs.parseplatform.org/php/guide/#session-storage-interface
But the way you are doing should also work. You will only have to make sure that, every time that a request comes, you will decode the JWT, get the Parse Session token from there, and use ParseUser::become to set the current user: https://docs.parseplatform.org/php/guide/#setting-the-current-user

Related

How can I re-acquire a Shopify OAuth access token for a store that has previously installed my application?

I requested authorization for a public application to be able to access store data via the Shopify API.
The store successfully authorized my application via an authorization request URL such as
https://some-store.myshopify.com/admin/oauth/authorize?client_id=123abc&scope=read_inventory%2Cread_products&redirect_uri=http%3A%2F%mysite.com%2Fauth.php&state=123456
and the response was passed back to my application. This response (containing the code that can be exchanged for a permanent access token) was mishandled by my application (an error on the page meant that the access token was not stored).
Everything I read regarding requesting these tokens involves authorization by the store - but given the store has already authorized my application, passed back the code and that code has already successfully been exchanged for a token: is there a way my application can request that same token or a fresh one using my API keys given that the application is already authorized?
The only method I currently can find for requesting a token requires starting back at the beginning and fetching a code for exchange etc.
I working in PHP and using Luke Towers' php shopify wrapper
This stage was completed successfully:
function check_authorization_attempt()
{
$data = $_GET;
$api = new Shopify($data['shop'], [
'api_key' => '123',
'secret' => '456',
]);
$storedAttempt = null;
$attempts = json_decode(file_get_contents('authattempts.json'));
foreach ($attempts as $attempt) {
if ($attempt->shop === $data['shop']) {
$storedAttempt = $attempt;
break;
}
}
return $api->authorizeApplication($storedAttempt->nonce, $data);
}
$response = check_authorization_attempt();
and I would have been able to read the access token from :
$access_token = $response->access_token;
But this was the stage at which my application hit an error in accessing a database in which to write said token.
I cannot repeat it without repeating the auth request because the data in $_GET that's passed to this function comes from Shopify's response to the shop owner authorizing the access, and includes amoung other things the code for exchange.
You have to re-ask for authorization. It is no one's fault but yours that your persistence layer code was incorrect. So there is nothing you can do to change that. Ensure your code works. Since the client has no token in your App persistence layer, your App will retry the authorization token exchange. They do not have to delete your App first. So basically, the next time your client tries to use the App, YES they will asked to approve it, but who cares, they will, and you'll get a good auth token to store. You have fixed your code (right), so that will work. You are one step closer to glory.
Shopify does return the Permanent Access Token, but the ACCESS_MODE must be "Offline" for the token to be permanent.
With ACCESS_MODE offline, your app receives the permanent access token
to make requests whenever you want, without the user's permission.
Documentation:
https://shopify.dev/tutorials/authenticate-with-oauth#step-2-ask-for-permission
https://shopify.dev/concepts/about-apis/authentication#api-access-modes

Overcome HTTP basic auth when calling WooCommerce API

I‘m trying to call the WooCommerce/Wordpress API, but the online shop that I‘m trying to reach has HTTP Basic Autj turned on. That means, I need to authenticate once to overcome the HTTP authentication and then I need to authenticate a second time using the api key in order to use the api. Is there a possibility to make an api call whilst overcoming two levels of authentication?
The problem is that if I try to authenticate, I use the following code:
$headers = array('Accept' => 'application/json');
$options = array('auth' => array($username, $password));
$request = Requests::get("$url/$api/$model", $headers, $options);
then I get a 401 (unathorised) response from the api, because I didn't send the api token in my request. But if I use the api token and secret instead of the username and password, I don't even get near the api because I don't overcome the http basic authentication.
Thanks for yout help!
From the looks of it, you're having an issue calling your website due to HTTP Basic Auth.
When it comes to authentication on https://your.site, you can connect to https://your.site and enter foo as the user and bar as the password, OR you can connect to https://foo:bar#your.site.
Hope I helped!
I can't comment on your question for clarification as I don't have the rep. So here goes with an answer!
I think the answer is that you will not overcome two levels of authentication in one call. You will likely contact the server first for an access token using your username and password.
Basic authorization usually means that in the initial http request you set the headers to include 'Authorization': 'Basic _______________________' and then in place of the underscores put a long alphanumeric string that is generated by base64-encoding your username and password (that you would log into WooCommerce with I presume) like so: username:password, and including that colon in between.
If I actually base64 encode username:password it comes out to dXNlcm5hbWU6cGFzc3dvcmQK
so when setting your initial http request headers, include:
'Authorization' : 'Basic dXNlcm5hbWU6cGFzc3dvcmQK'
Except base64 encode you're own username and password (separated by the colon!).
Assuming this works, the api may return an access token to you in a few ways. But if you follow the docs you should be able to figure it out from this point.
Again, really not clear on what you're question is exactly but can't comment so I took a shot. Good luck

RESTful service - using Phil Sturgeon Rest Server : Logic / function for validating the users with their username and password?

I'm writing a simple RESTful service, using Phil Sturgeon Rest Server. Can anyone provide me a solution for login using username and password. I am able to get all the json reponse without login.
Porblem 1 : $config['rest_auth'] = 'basic';
An Error Was Encountered
The configuration file ldap.php does not exist.
The same happens with $config['rest_auth'] = 'digest';
I haven't used "ldap" earlier and don't know how it works apart from a few basic information. So could you please tell me what could be the reason for this error ?
Tried out Solutions
I changed the value of $config['auth_source'] = 'ldap'; to $config['auth_source'] = ''; , Now REST Login Usernames are working for both basic and digest , ie;
$config['rest_auth'] = 'basic'; or $config['rest_auth'] = 'digest';.
$config['rest_valid_logins'] = ['admin' => '1234','sudheesh'=>'test'];
Prevailing issue : unable to use session for authentication
Tried the commented notes from Phil Sturgeon ie;
Note: If 'rest_auth' is set to 'session' then change 'auth_source' to
the name of the session variable
How the session is created in MODEL, it is here :
if ($query->num_rows() == 1) {
// If there is a user, then create session data
$row = $query->row();
$data = array(
'id' => $row->id,
'name' => $row->full_name,
'email' => $row->email,
'phone' => $row->phone,
'acc_status' => $row->rec_status,
'validated' => true
);
$this->session->set_userdata($data);
//$this->session->set_authkey('1e957ebc35631ab22d5bd6526bd14ea2');
//print_r($data);
return $data;
Question is : How can I change the 'auth_source' to
the name of the session variable ,
Right now it is $config['auth_source'] = ''
Do i have to change it to : $config['validated'] , if I do this am not getting the access , I have read here that:
If you're tying this library into an AJAX endpoint where clients
authenticate using PHP sessions then you may not like either of the
digest nor basic authentication methods. In that case, you can tell
the REST Library what PHP session variable to check for. If the
variable exists, then the user is authorized. It will be up to your
application to set that variable. You can define the variable in
$config['auth_source']. Then tell the library to use a php session
variable by setting $config['rest_auth'] to session.
Is there any suggestions ?
Problem 2 : How can I grant API access to users with a valid username and password ?
Can anyone provide me with a function or detailed information on how to implement this ?
Other Doubts :
$config['rest_valid_logins'] = ['admin' => '1234'];
The description for this 'REST Login Usernames' says if ldap is configured this is ignored.
Question : How can I use this Array of usernames and passwords for login, without configuring LDAP.
REST Login Class and Function
This says, If library authentication is used define the class and function name.
The function should accept two parameters: class->function($username, $password).
In other cases override the function _perform_library_auth in your controller.
For digest authentication the library function should return already a stored md5(username:restrealm:password) for that username.
e.g: md5('admin:REST API:1234') = '1e957ebc35631ab22d5bd6526bd14ea2'
$config['auth_library_class'] = '';
$config['auth_library_function'] = '';
Question: Can I use this to allow users with a valid username and password to access the API ? If Yes , Do you have any functions already written to help in this scenario , any help would be highly appreciated. Thank you very much .
If you know answers for any of my issues, please help. Thanks again.
Rather than attempt to address every single question posted by Sudheesh, I would like to propose an alternate solution.
Disclaimer: This is a commercial Joomla plugin, so please keep that in mind before proceeding...
Having experienced the same challenge as yourself, I ended up building a RESTful API framework for Joomla, powered by the Slim PHP micro-framework. This allowed me to leverage all the power of Slim, including it's standards-compliant routing architecture, request-type handling and much, much more. This also solved the problem of deal with authentication, access control, content management, database access, etc. because it runs on the Joomla CMS & Platform framework.
This solution provides exactly what you are looking for, easily extensible through plugins and is built on an already popular and well support RESTful API framework (Slim).
For more information on the micro-framework I used:
http://slimframework.com
For more information on the Joomla RESTful API package:
http://getcapi.org
What does it provide?
Control Panel for managing access tokens, API rate limitation and other Slim parameters
Pluggable framework allowing for easy incorporation of new web service routes (include new ones to be released soon, for MySQL, MSSQL, LDAP, etc.)
Based on Joomla. This means you don't have to worry about writing the authentication, access control, content management or other framework. It's already done!
Examples of how username and password can be passed through to create a logged in session via a URL request:
GET user/login/:username/:password
"User login authentication via Joomla authentication plugins with username and password. Note that since credentials are passed into the URL, be aware that they can be stored in server logs. API traffic must traverse a secure (HTTPS) connection."
Response: JSON
Example request:
GET https://yourdomain.com/api/v1/user/login/dynus.borvalds/3jf9LfjNdiw
Example response:
{"msg": "Authenticated","jresponse": true,"session":"1a36eab5e2b102a979918ee049f15e27","error": false,"status": 200}
The session ID can then be used to force log-out for that session using the method:
GET user/logout/:user/:session
Hope this gets you pointed in the right direction. Let me know if you have any questions.

How to implement 'Token Based Authentication' securely for accessing the website's resources(i.e. functions and data) that is developed in PHPFox?

I want to use methods and resources from the code of a website which is developed in PHPFox.
Basically, I'll receive request from iPhone/Android, I'll get the request and pass to the respective function from the PHPFox code, take the response from that function and return it back to the device.
For this purpose I've developed REST APIs using Slim framework.
But the major blocker I'm facing currently is in accessing the resources(i.e. functions and data) of PHPFox website.
I'm not understanding how should I authenticate the user using 'Token Based Authentication' in order to access the website's resources.
If someone could guide me in proper direction with some useful working example it would be really helpful for me.
N.B. : The proposed implementation of 'Token Based Authentication' should be very secure and fast in speed. The security should not be compromised in any way.
Following is the code I tried on my own but I don't know whether it's right or wrong. Is my approach correct or wrong. Please someone analyse it and let me know your feedback on it.
To create a token i use this function which takes as parameters, the user's data
define('SECRET_KEY', "fakesecretkey");
function createToken($data)
{
/* Create a part of token using secretKey and other stuff */
$tokenGeneric = SECRET_KEY.$_SERVER["SERVER_NAME"]; // It can be 'stronger' of course
/* Encoding token */
$token = hash('sha256', $tokenGeneric.$data);
return array('token' => $token, 'userData' => $data);
}
So a user can authentified himself and receive an array which contains a token (genericPart + his data, encoded), and hisData not encoded :
function auth($login, $password)
{
// we check user. For instance, it's ok, and we get his ID and his role.
$userID = 1;
$userRole = "admin";
// Concatenating data with TIME
$data = time()."_".$userID."-".$userRole;
$token = createToken($data);
echo json_encode($token);
}
Then the user can send me his token + his un-encoded data in order to check :
define('VALIDITY_TIME', 3600);
function checkToken($receivedToken, $receivedData)
{
/* Recreate the generic part of token using secretKey and other stuff */
$tokenGeneric = SECRET_KEY.$_SERVER["SERVER_NAME"];
// We create a token which should match
$token = hash('sha256', $tokenGeneric.$receivedData);
// We check if token is ok !
if ($receivedToken != $token)
{
echo 'wrong Token !';
return false;
}
list($tokenDate, $userData) = explode("_", $receivedData);
// here we compare tokenDate with current time using VALIDITY_TIME to check if the token is expired
// if token expired we return false
// otherwise it's ok and we return a new token
return createToken(time()."#".$userData);
}
$check = checkToken($_GET['token'], $_GET['data']);
if ($check !== false)
echo json_encode(array("secureData" => "Oo")); // And we add the new token for the next request
Am I right?
Thanks.
1st you should understand what's token based authentication. It could be explained as below.
The general concept behind a token-based authentication system is
simple. Allow users to enter their username and password in order to
obtain a token which allows them to fetch a specific resource -
without using their username and password. Once their token has been
obtained, the user can offer the token - which offers access to a
specific resource for a time period - to the remote site.
Read more
Now let's see what are the steps of implementing it in your REST web service.
It will use the following flow of control:
The user provides a username and password in the login form and clicks Log In.
After a request is made, validate the user on the backend by querying in the database. If the request is valid, create a token by
using the user information fetched from the database, and then return
that information in the response header so that we can store the token
browser in local storage.
Provide token information in every request header for accessing restricted endpoints in the application.
If the token fetched from the request header information is valid, let the user access the specified end point, and respond with JSON or
XML.
See the image below for the flow of control
You might be wondering what's a JWT
JWT stands for JSON Web Token and is a token format used in
authorization headers. This token helps you to design communication
between two systems in a secure way. Let's rephrase JWT as the "bearer
token" for the purposes of this tutorial. A bearer token consists of
three parts: header, payload, and signature.
The header is the part of the token that keeps the token type and encryption method, encoded in base64.
The payload includes the information. You can put any kind of data like user info, product info and so on, all of which is also stored in
base64 encoding.
The signature consists of combinations of the header, payload, and secret key. The secret key must be kept securely on the server-side.
You can see the JWT schema and an example token below;
You do not need to implement the bearer token generator as you can use php-jwt.
Hope the above explains your confusion. if you come across any issues implementing token based authentication let me know. I can help you.

Zend HTTP Client password

Im trying to connect from PHP(Zend Framework) code to an aspx Web Service. I need to send via post a few parameters to the page( email, password). I have tried to use Zend_Http_Client, and do this:
$client = new Zend_Http_Client('https://thesiteurl.asmx/Login');
$client->setMethod(Zend_Http_Client::POST);
$client->setAuth($username, $password);
$client->setParameterPost(array('email' => 'email', 'password' => 'password'));
$response = $client->request();
$this->view->response = $response;
where $username, $password are the username and password I use to log in to the web service(it has a pop-up window that asks me for username and password).
This code gives me the unauthorized page. So im asking where am I using the site username and password wrong? How can I use them?
edit:
The Auth is auth-basic.
Edit2:
I talked to the owner of the web service he says that everything is UTF-8 is this a problem, isnt it is a default? If not how do i do that?
You could check if a referer-header is needed, or it might be that it also needs a cross-site request forgery number. Simply dump the request that is made by your browser when you login and dump the request that your script is generating, compare those and it should work out.
For the browser-request dump you could use livehttpheaders plugin for firefox.
Depends on what that pop up box really is.
You probably need to study the HTTP Authentication. Currently, Zend_Http_Client only supports basic HTTP authentication. This feature is utilized using the setAuth() method, or by specifying a username and a password in the URI. The setAuth() method takes 3 parameters: The user name, the password and an optional authentication type parameter. As mentioned, currently only basic authentication is supported (digest authentication support is planned).
// Using basic authentication
$client->setAuth('shahar', 'myPassword!', Zend_Http_Client::AUTH_BASIC);
// Since basic auth is default, you can just do this:
$client->setAuth('shahar', 'myPassword!');
// You can also specify username and password in the URI
$client->setUri('http://christer:secret#example.com');
Source.
If this is not an HTTP auth and is somothing else, try to use cURL, wget or linx to see exactly what is happening on the page and now you can simulate it using Zend_Http_Client.
Sometimes you have to send cookies, execute some Js or follow some redirects. Zend_Http_client can do all this things.
have you tried this?
$config = array(
'adapter' => 'Zend_Http_Client_Adapter_Socket',
'ssltransport' => 'tls'
);
$client = new Zend_Http_Client('https://thesiteurl.asmx/Login', $config);
$client->setAuth('shahar', 'myPassword!', Zend_Http_Client::AUTH_BASIC);
also I am confused, is this popup a http basic auth, or something that is self designed?
since for basic auth you normally wouldn't send any post params...
the real URL of the site would help very much for finding the solution...
If you can access the servis using browser, use firebug to check the request and response. There might be some other parameters involved, eg cookie.
The best way to tackle these things is by just using the packet sniffer (tcpdump, ethereal, ...) to see what's happening on the line. Then compare the request/response you observe in a working scenario (e.g. from your browser) to the request/reponse which is not working.
This will very quickly reveal the precise difference at the HTTP level. Using this information you can either find out what to fix in your handling of Zend_Http_Client, or find out that Zend_Http_Client doesn't support a particular feature or authentication scheme.

Categories