Silex token authentication - symfony

I create my first app with silex. Only logged in users can use the app. In the first page i create a login form, so the user can authenticate. My security provider look like:
$app->register(new Silex\Provider\SecurityServiceProvider(), array(
'security.firewalls' => array(
'secure_area_edison' => array(
'pattern' => '^/admin/',
'form' => array('login_path' => '/', 'check_path' => '/admin/login_check'),
'logout' => array('logout_path' => '/admin/logout', 'invalidate_session' => true),
'users' => function () use ($app) {
return new App\Services\UserProvider($app['db']);
},
),
)
));
Every url after '/admin' require that the user was successfull authenticated. Everything works fine and now i want to extend my app with an API. I create a new controller which retrieves data from database and return a JSON reponse, this work also fine.
But how can the user authenticate for this API? Should i create a new column in my user table like "hash" or "token"? Users which will retrieve the JSON Response must send the token in every get request, is this the correct way?
The url can look:
/admin/api/allProducts/token/<TOKEN>

you should use token base authentication instead of passing token in every get request.
refer : https://github.com/thcolin/silex-simpleuser-jwt

Related

Using a single Cloudflare account in Wordpress with WP Super Cache with visible API key

We are starting to use Cloudflare on a few Wordpress client accounts and notice in the CDN settings that my email address and API key are visible to the client.
Is this a potential security issues where others can see my Cloudlflare email address and API key? Should I be using 1 Cloudflare account per client account?
Here is a screenshot (i have blurred the API key and deleted the email input box in the console) but both these values are visible to the customer.
What is the worse thing they could do with these 2 pieces of data?
you have to use tokens instead of global api key. you strict token to certain zone only
This only will NOT solve the problem, you have to manually modify wp fastest cache plugin to modify the request to match API tokens usage.
the requests can be found in inc\cdn.php
The modified file:
https://gist.github.com/ahmed-abdelazim/7c8170f7fc4e821c6b015d770fcbf14a
so
$header = array("method" => "DELETE",
'headers' => array(
"X-Auth-Email" => $email,
"X-Auth-Key" => $key,
"Content-Type" => "application/json"
),
"body" => '{"purge_everything":true}'
);
is converted to
$header = array("method" => "DELETE",
'headers' => array(
//"X-Auth-Email" => $email,
"Authorization" => "Bearer ".$key,
"Content-Type" => "application/json"
),
"body" => '{"purge_everything":true}'
);
and this occured five times in the plugin in the cdn.php file
simply creating API Token worked for me. There are some pre made template. There was for wordpress one as well. Just selected and created and added it to wp fastest cache and that worked.

How to get current logged in user from WordPress via custom endpoints?

I have an endpoint in my WordPress plugin, and using it. I want to get the user who is currently logged in the WordPress. My endpoint looks like this:
add_action( 'rest_api_init', function () {
register_rest_route( 't2mchat/v2', '/get_curr_user', array(
'methods' => 'GET',
'callback' => 'get_curr_user'
));
});
The callback function:
function get_curr_user(WP_REST_Request $request){
$user = wp_get_current_user();
return $user;
}
This gives me back user ID as 0.
I read the article on WordPress official website about Authentication , and learned that I need to pass nonces, but since I am a new to this, I could not understand everything it says.
Also, I am calling this endpoint in my React app like this:
loadData() {
return fetch(`/wordpress/wp-json/t2mchat/v2/get_curr_user`)
.then(response => response.json())
.then(responseJson => {
this.setState({ curr_user: responseJson });
//console.log(this.state.curr_user, "curr user role");
})
.catch(error => {
console.error(error);
});
}
I am not sure how do I pass nonces in the request, so I can get the currently logged in user.
Can anyone with experience/idea suggest what changes I need to make in my code?
An example would be highly appreciated.
Thank you.
in your PHP file include the wp-load.php
include_once("wp-load.php");
then you can access to all native Wordpress Function just call them.
So you have to be able to retrieve the current logged in user by wp_get_current_user();
I used session storage to store user data when the wordpress initializes and retrieved from my endpoint. It worked for me.

401(woocommerce_api_user_cannot_read_product) response--Woocommerce REST API

the API works when ck_ and cs_ keys are for Admin and returns the std class object but when keys are for a different user returns You do not have permission to read this product 401(woocommerce_api_user_cannot_read_product) Error response: even when user has read/write privileges. but goes ahead to create the product in the database. Any help on this issue is highly appreciated
require_once( 'lib/woocommerce-api.php' );
$options = array(
'debug' => true,
'return_as_array' => false,
'validate_url' => false,
'timeout' => 30,
'ssl_verify' => false,
);
try {
$client = new WC_API_Client( $the_url, 'ck_xxxx', 'cs_xxxx', $options);
Try adding into your $options array:
$options['query_string_auth'] = true;
As noted in the documentation this will "Force Basic Authentication as query string true" in other words it will append your consumer key and consumer secret to your request URL as a query string. This is only supported on HTTPS.

Sylius: how to notify payment if capture token is not in the url?

I am creating my own payment bundle with Payum. I managed to correctly generate the payment order with my payment entity and my bundle redirects correctly to the payment page of my entity (where the user enters their card and PIN number). The problem is that I can not validate the payment. My payment entity only allows me to configure a single payment confirmation asynchronous call url (and it does not allow me to send a parameter with the notification url in each order).
How do I have to proceed to obtain the payment token? Is there any way to get the payment token from the order id and then validate it?
Ok, i think i've made it. This is the "solution":
First of all, i had to create an url for notifications with a controller atached.
payum_ceca_notification_url:
path: /payum/ceca/bank-notification
methods: [GET, POST]
defaults:
_controller: CecaPlugin:Notify:do
Then in my doAction:
public function doAction(Request $request):Response
{
$params = $request->request->all();
$order_id = (int) $params['Num_operacion'];
$payment = $this->container->get('sylius.repository.payment')->findOneBy(['id' => $order_id]);
$details = $payment->getDetails();
$cecaOptions = array(
'Environment' => $details['Environment'],
'MerchantID' => $details['MerchantID'],
'AcquirerBIN' => $details['AcquirerBIN'],
'TerminalID' => $details['TerminalID'],
'ClaveCifrado' => $details['ClaveCifrado']);
$apiCeca = new ApiCeca($cecaOptions);
$apiCeca->setFormHiddens(array(
'Num_operacion' => $details['Num_operacion'],
'Importe' => $details['Amount'],
'URL_OK' => $details['url_ok'],
'URL_NOK' => $details['url_nok'].'?pagocancelado=1'
));
// check my sign vs the sign sent to me by payment entity
$apiCeca->checkTransaction($params);
$payment->setState(PaymentInterface::STATE_COMPLETED);
$payment->getOrder()->setPaymentState(OrderPaymentStates::STATE_PAID);
$manager = $this->container->get('sylius.manager.payment');
$manager->persist($payment);
$manager->flush();
return new Response();
}
I know that it is not the most elegant solution but it is a solution that works, marks the order as paid.

Laravel 5.3 Passport api routes are returning Unauthenticated error

I am new in Laravel Passport and I am able to get the the tokens from Laravel like below with Postman.
With this token, I tried to access my api route user-details
Route::group(['middleware'=>'auth:api'],function(){
Route::get('user-details','ApiController#getUsers');
});
Here I am getting
{
"error": "Unauthenticated."
}
Screenshot:
What is the issue actually ?
Since you didn't mention this step, I am guessing you might have missed this step.
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
Read the documentation fully.
https://laravel.com/docs/5.5/passport

Resources