Magento 2 REST API call to get logged in customer ID - php

I want to make a REST call from outside of Magento (but on the same domain) to get the currently logged in customer's ID. I don't want them to have to login again or provide a password, I just need to get their ID so I can redirect them somewhere based on their ID.
I see this endpoint in the URL:
http://.../rest/V1/customers/me
but when I cURL that URL I get:
Consumer is not authorized to access %resources
Do I still need to get a token to access this even though it is anonymous and based on the session? If so, what does this PHP call look like?
I just need to prove they are logged in and grab their ID.

That should work, considering you are sending the PHPSESSID together with you request. As you said you're using cURL, that is probably not the case.
You could easily achieve that by making an ajax call to the API, something similar to the following:
jQuery.ajax({
url: 'http://dev.magento2.com/rest/V1/customers/me',
type: 'get',
error: function() {
alert('User not Logged In');
},
success: function() {
alert('User logged in');
}
});
If you need to keep the requests on the server side, then you should add PHPSESSID to your requests:
$ch = curl_init('http://dev.magento2.com/rest/V1/customers/me');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
$json = json_decode($result);
if (isset($json->id)) {
echo 'User logged in';
} else {
echo 'User not logged in';
}
(source for the cURL request: https://community.magento.com/t5/Programming-Questions/REST-API-call-to-get-logged-in-customer-ID/m-p/62092#M1813)

Related

Access Microsoft Graph resources with an App access token (no user sign-in)

I own an institutional e-mail account and I want to access its content (and send emails) using a PHP web application I'm writing, and I want it to access this account without sign-in from the user (they will be logged to my application, that will send predefined messages based upon user's actions).
I registered the application using Microsoft Application Registration Portal using this institutional account credentials, and got my client_id and client_secret (password).
I'm using the code below to perform authentication based on these instructions:
function preformat($string) {
return "<pre>".htmlentities($string)."</pre>";
}
function getGraphAccessToken($domain, $client_id, $password) {
$graph_endpoint="https://graph.microsoft.com/.default";
$token_endpoint = "https://login.microsoftonline.com/".$domain."/oauth2/v2.0/token";
$token_postdata = implode("&",[
"grant_type=client_credentials",
"client_id=".urlencode($client_id),
"client_secret=".urlencode($password),
"scope=".urlencode($graph_endpoint)
]
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $token_endpoint);
curl_setopt($ch, CURLOPT_POSTFIELDS, $token_postdata);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$token_json = curl_exec($ch);
curl_close($ch);
$token_object = json_decode($token_json);
return "Authorization: ".$token_object->token_type." ".$token_object->access_token;
}
function queryGraph($auth_header, $feed){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, "https://graph.microsoft.com/v1.0/".$feed);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($auth_header,"Accept:application/json;odata=minimalmetadata","Content-Type:application/json;odata=minimalmetadata","Prefer:return-content"));
$graph_query = curl_exec($ch);
curl_close($ch);
return $graph_query;
}
$auth_header=getGraphAccessToken($domain,$client_id,$client_secret);
echo preformat($auth_header);
$query_me=queryGraph($auth_header,"me");
echo preformat($query_me);
This code succeeds to grab the access token and requests from https://graph.microsoft.com/v1.0/me/ expecting to receive the institutional account's info (as a success test). However, I get the following response:
{
"error": {
"code": "BadRequest",
"message":
"Current authenticated context is not valid for this request.
This occurs when a request is made to an endpoint that requires user sign-in.
For example, /me requires a signed-in user.
Acquire a token on behalf of a user to make requests to these endpoints.
Use the OAuth 2.0 authorization code flow for mobile and native apps
and the OAuth 2.0 implicit flow for single-page web apps.",
"innerError": {
"request-id": "3073f561-43db-49d3-9851-7f50037abb61",
"date": "2018-12-31T17:28:45"
}
}
}
What am I missing or doing wrong here?
You cannot use /me with app-only authentication, you need to reference the user via their userPrincipalName - /users/{upn}. After all, how would Graph know which "me" you are referring too?

get specific data from REST API

I want to get specific data from rest api after user login using cookie auth but I end up with Field 'fieldname' does not exist or this field cannot be viewed by anonymous users.
Below you can see the code I wrote in ajax and php to get data. I know my script is probably awful as I used curl request for the first time so bear with me, I want someone to tell me where I am doing wrong or better explain to me how to get and post data to server with curl and get and specific data display would be appreciated.
$('#user-profile').click(function(){
$.ajax({
type: "POST",
url: "jiraticket.php",
data: $('#login-form').serialize(),
success: function(data){
alert(data);
}
});
});
and here is the script
<?php
session_start();
$url = 'http://base-url/rest/api/2/search?jql=issuetype%20=%20Epic%20AND%20status%20in%20(%22In%20Progress%22,%20Backlog,%20%22On%20hold%22,%20%22To%20Do%22)';
$curl_session = curl_init($url);
curl_setopt($curl_session, CURLOPT_HEADER, 0);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
if(isset($_COOKIE['JSESSIONID']))
$cookie_string='JSESSIONID='.$_COOKIE['JSESSIONID'];
else
$cookie_string="";
curl_setopt($curl_session, CURLOPT_HTTPHEADER, array('Content-Type: application/json' ,'Authorization: Cookie'), array('cookie:'.$cookie_string));
$response = curl_exec($curl_session);
curl_close($curl_session);
if ( !$response ) {
die('Nothing was returned.');
}
$result = json_decode($response, true);
print_r($result);
$response printing "errorMessages":["Field 'issuetype' does not exist
or this field cannot be viewed by anonymous users."]
Well, it means the API does not want to give you the value of issuetype.
Might be a typo or something, but that's not an error with your curl call, it's a problem with the API provider

How can I login the user by API without storing its info in the wordpress database.

Just like facebook login I want my user to get logged into my wordpress site by api. I want to get logged-in without storing the any info of user in the wordpress database.
here is what I tried
$ch = curl_init();
$username = $_REQUEST['value'];
curl_setopt($ch, CURLOPT_URL, 'http://api.ig.sapps.com/userLogin?emailOrUsername='.$login_data['user_login'].'&password='.$login_data['user_password'].'&api_token=12345&device_id=0&device_type=0');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
$result = json_decode($res);
if ($result->code == 400) {
$login_error = $result->message;
$all_errors = array($login_error);
}
if ($result->code == 200) {
wp_set_current_user($result->data->id, $result->data->username);
wp_set_auth_cookie($result->data->id);
do_action('wp_login', $result->data->username);
But I am not able to logged in. Please help me out.
There are so many Authentication technique... but I will explain only 2 way. (If user will login you app this user will anyway use his/hers private data other way meaningless)
1) Common Token Based Authentication Which you have to persist some data on BackEnd to check this data in every request.
2) JWT - Some Third Part Authorization Centers uses this technique. With this way you have not persist user data. Validation takes with your (Third Part Authorization Center's) unique and private SIGNATURE.
With second way you or Third part Authorization Centers saves some unique and Secured Signature and validates this user login and api call request with this sign.

It is possible to get my current location via the Facebook Graph API?

I am trying to build a portion into my personal website that shows the locations I have tagged in my posts on facebook. My understanding is that I need to do an oAuth Request on the server to get the AccessToken:
UPDATE
I built a php file that gets a file with the token in it and refreshes it. I can call this file with a cron job every hour and have an unlimited token. It looks like this:
$appID = "APPID";
$appSecret = "APPSECRET";
$currentToken = file_get_contents(__DIR__."/token.txt");
$url = "https://graph.facebook.com/oauth/access_token?client_id=".$appID."&client_secret=".$appSecret."&grant_type=fb_exchange_token&fb_exchange_token=".$currentToken;
$ci = curl_init();
curl_setopt($ci, CURLOPT_URL, $url);
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ci, CURLOPT_TIMEOUT, 10);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ci, CURLOPT_FOLLOWLOCATION, TRUE);
$newtoken = curl_exec($ci);
curl_close ($ci);
$newtoken = str_replace("access_token=","",$newtoken);
$newtoken = substr($newtoken, 0,strpos($newtoken, "&expires=",0));
if($newtoken == "")
{
echo "error";
}
else
{
$file = __DIR__."/token.txt";
file_put_contents($file, $newtoken);
echo $newtoken;
}
If the Access Token has the form {app_id}|{app_secret}, you're not using a User Access Token, but an App Access Token.
Seems like you don't implement the proper Login process to gather the User Access Token. Stick to the provided sample code of the FB PHP SDK.
See
https://developers.facebook.com/docs/php/gettingstarted/4.0.0
https://developers.facebook.com/docs/facebook-login/access-tokens#usertokens

Check whether user is logged in another domain

I am using a remote login feature in my website for logging into an onapp server from my site.. This will actually fetch the form using CURL and submitting it with user name and password. It is working fine. Now my site has got different services for a single user and so there is multiple accounts in the onapp server. So I need a method to check if there is a session is existing in the onapp server(if a user is already logged in).If a user is already logged in onapp, will not allow another login and will show there is a user already logged in. So it is needed to logout the user and login using the new credentials. Any idea how this can be done. ?
This one I think it could help you
// REST Server URL
$request_url = 'http://localhost:3000/rest_api/user/login';
// User data
$user_data = array('username' => 'jimthunderbird',
'password' => '123456', );
// cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_POST, 1);
// Do a regular HTTP POST
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($user_data)); // Set POST data
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curl);
print $response;
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check if login was successful
if ($http_code == 200) {
// Convert json response as array
$logged_user = json_decode($response);
} else {
// Get error msg
$http_message = curl_error($curl);
die($http_message);
}
print_r($logged_user);

Categories