How set session keycloak after connexion with custom login form - single-sign-on

I am developing a prestashop sso module using keycloak, to check if a user is already logged in or not with the keycloak interface, I used the keycloak.js script:
const config = { url: urlKeycloak, realm: realm, clientId: clientId, "enable-cors": true, "cors-max-age": 100, "cors-allowed-methods": "POST, PUT, DELETE, GET"};
const keycloak = new Keycloak(config);
keycloak.init({onLoad: 'check-sso', checkLoginIframe: false}).success((authenticated) => {
console.log(authenticated);
}).catch(function(e) {
alert('failed to initialize');
console.log(e);
});
It works perfectly.
Now I want to login to keycloak through the prestashop login form (username and password) (I don't want to redirect to the login page of keycloak), so I used the keycloak REST API to get access_token ..., but my js script does not detect my login on keycloak, a priori It's missing brosser sessions of keycloak. Is there a keycloak REST api which saves sessions through the access_token?
Here is my connection code through the login form
$data['username'] = 'username';
$data['password'] = 'password';
$data['grant_type'] = "password";
$data['client_id'] = 'clientId';
$data['client_secret'] = 'client_secret';
$link = url_keycloak/realms/realm/protocol/openid-connect/token";
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_URL, $url);
$headers = array(
'Content-Type: application/x-www-form-urlencoded',
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($curl);
curl_close($curl);

Related

How to generate token for rest call in codeigniter?

I have to call rest api function in codeigniter project . Data is returning from the api call using Postman . In Postman first i generate a token and put that generated token in the rest call. I have to do the same process in codeigniter. First i have to generate token and pass that token in second api call to get the desired result.
My Controller code :
public function getToken()
{
$url='http://localhost:8080/myapplication/rest/api/validate-request';
$key=$this->get_data($url);
}
public function get_data($url)
{
//create a new cURL resource
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, R_U_NAME.':'.R_U_PWD);
$result = curl_exec($ch);
$result = json_decode($result);
//var_dump($result);
//close cURL resource
curl_close($ch);
}
Here var_dump($result) is returning null value.
I donot had to pass username and password for authentication .Instead i had to post postman username and password in my function. Now I am getting the token back from the postman.
private function get_data($url)
{
$member_data = array(
'username' => R_U_NAME,
'password' => R_U_PWD
);
//create a new cURL resource
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $member_data);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

Magento 2 rest api Consumer is not authorized to access %resources<

I want to get the products from magento 2 that is in my localhost. but when i put /rest/V1/products? it gives me
<response>
<message>Consumer is not authorized to access %resources</message>
<parameters>
<resources>Magento_Catalog::products</resources>
</parameters>
</response>
i have made roles and also integration. i don't know how to access these resources. i have to get these products in my ionic app
That error is fairly self explanatory - you haven't authenticated.
Here's an example of how to authenticate with an admin user and fetch products using curl;
// Fetch the user auth token
$userData = array("username" => "USER", "password" => "PASS");
$ch = curl_init("http://DOMAINNAME.com/index.php/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));
$token = curl_exec($ch);
// Now use the token to get all products
$ch = curl_init("http://DOMAINNAME.com/index.php/rest/default/V1/products?searchCriteria");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
// Here are the results
$result = curl_exec($ch);
$result = json_decode($result, 1);
echo '<pre>';
print_r($result);
echo '</pre>';

Laravel rest api authentication

I am a beginner with building a rest api and authentication.
I've just been reading the following and explains a very simple setup:
laravel 5 rest api basic authentication
At the bottom the article explains not to send usernames and password with headers or in the url.
My question is basicly: can anyone give me an example how to use a cUrl request with the example above?
For example:
$service_url = 'http://example.com/api/conversations';
$curl = curl_init($service_url);
$curl_post_data = array(
'user' => 'user#user.com',
'passw' => '1234'
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
curl_close($curl);
Laravel is shipped with Guzzle – an advanced HTTP client library. It's probably more reasonable to use that than a low-level cURL.
To do basic auth with Guzzle:
$client = new GuzzleHttp\Client();
$response = $client->post('http://example.com/api/conversations', [
'auth' => [
'user#user.com',
'1234'
]
]);
The response will be in $response->getBody();
If your target endpoint uses SSL – it's not too bad sending the credentials in the headers, but the trendy way is to use temporary tokens (eg. API key or OAuth access token).
In addition to the accepted answer, you can also create a generic function to handle all your curl requests.
You can use the following function to call external webservices and return the data/authentication information.
/*=============================================
* Call External Webservices using CURL
*
* #param $requestURL, $header -> (OPTIONAL)
* #return json
#=============================================*/
public function curlRequest($requestURL, $headers = array())
{
$getData = curl_init($requestURL);
curl_setopt($getData, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($getData, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($getData, CURLOPT_SSL_VERIFYHOST, false);
if (count($headers) != 0) {
curl_setopt($getData, CURLOPT_HTTPHEADER, $headers);
}
$response = curl_exec($getData);
return json_decode($response);
}
Use case specific example to use the above function for authentication:
$requestURL = 'http://www.example.com/api/userLogin';
$userAuthInfo = [
'email'=> 'example#example.com',
'password'=>'123456'
];
$result = $this->curlRequest($requestURL, $userAuthInfo);
dd($result); //Print the Result of the Authentication request

Translate cURL request to Guzzle

I am trying to use Guzzle instead of directly using cURL to achieve and HTTP request. How do I make this same type of request but with Guzzle? Or should I just stick to cURL?
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, $url);
// don't verify SSL certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// Return the contents of the response as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Follow redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// Set up authentication
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$token:X");
I keep running into 401 Unauthorized error. I know I have correct credentials. What makes me think I am not on the right track is the Guzzle docs stating: auth is currently only supported when using the cURL handler, but creating a replacement that can be used with any HTTP handler is planned. But from my understanding Guzzle defaults with cURL.
$guzzleData = [
'auth' => [$token, 'X'],
'allow_redirects' => true,
'verify' => false,
];
$client = new \Guzzle\Http\Client();
$request = $client->get($url, $guzzleData);
$response = $request->send();
Here is the solution:
$client = new \Guzzle\Http\Client();
$request = $client->get($url);
$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false);
$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
$request->getCurlOptions()->set(CURLOPT_RETURNTRANSFER, true);
$request->getCurlOptions()->set(CURLOPT_FOLLOWLOCATION, true);
$request->getCurlOptions()->set(CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$request->getCurlOptions()->set(CURLOPT_USERPWD, "$token:X");
$response = $request->send();
The solution I was able to get working for Guzzle6 is:
$headers = array();
$headers['grant_type'] = 'client_credentials';
$headers['client_id'] = $clientid;
$headers['client_secret'] = $clientSecret;
$response = $this->client->post($urlAuth, ['form_params' => $headers]);
$output = $response->getBody()->getContents();
ie the header array has to be wrapped in 'form_params'

Login on facebook using username and password. Is there any way to do that?

I have a mobile application where I want the user to send to the server his facebook credentials infos and the server will act in behalf of him in facebook (get friends list and so on).
I am researching about it, but I only find information about this oauth2, where the user logs himself in Facebook in a special link, so my app can access his FB information. This doesn't help me because I would like to access this information on the server side, not by the app itself. Is there any way that I can log in using username and password?
I have a WP7 application for facebook chat where I enter my username and password and I connect, so it should be some way to perform it, correct?
edit
Because it is against the TOS, I am thinking about doing the following:
My server sends to my client the URL so the user can login and allow my app to access its informations. After that, my server accesses it.
Would that be possible?
FB is removing the offline_access token.
No solution for this question i guess.
No offline_access, token expires in 60days, No access with username and password(AGAINST TOS)
This is against their tos, but you could use
<?php
/* EDIT EMAIL AND PASSWORD */
$EMAIL = "";
$PASSWORD = "";
function cURL($url, $header=NULL, $cookie=NULL, $p=NULL)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, $header);
curl_setopt($ch, CURLOPT_NOBODY, $header);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if ($p) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $p);
}
$result = curl_exec($ch);
if ($result) {
return $result;
} else {
return curl_error($ch);
}
curl_close($ch);
}
$a = cURL("https://login.facebook.com/login.php?login_attempt=1",true,null,"email=$EMAIL&pass=$PASSWORD");
preg_match('%Set-Cookie: ([^;]+);%',$a,$b);
$c = cURL("https://login.facebook.com/login.php?login_attempt=1",true,$b[1],"email=$EMAIL&pass=$PASSWORD");
preg_match_all('%Set-Cookie: ([^;]+);%',$c,$d);
for($i=0;$i<count($d[0]);$i++)
$cookie.=$d[1][$i].";";
/*
NOW TO JUST OPEN ANOTHER URL EDIT THE FIRST ARGUMENT OF THE FOLLOWING FUNCTION.
TO SEND SOME DATA EDIT THE LAST ARGUMENT.
*/
echo cURL("http://www.facebook.com/",null,$cookie,null);
?>
http://www.daniweb.com/web-development/php/code/290893
A solution you could use that is TOS friendly would be to have the user sign up on your website and grant the offline_access token using the Facebook SDK. Your mobile app could use that token to make requests on behalf of the user in you mobile app. I would be clear as your requesting the permission with what you intend to with it.