Oath2 redirect call is missing parameters - php

I am trying to authenticate with a family history web service that authenticates using OAuth2. The basic workflow of the authentication is that I submit a get request against the web service requesting an authentication session. It returns in the body of the response HTML Code with some login components for user name and password. My PHP application then echoes the html code to the browser. The end user can then enter his or her user name and password, then submit to the web service. This is where the behavior becomes unclear. In theory, The web service should redirect to a predefined redirect URI with some parameters included in the URL. In practice, however, submitting the password redirects to the pre registered redirect URI, but there are no parameters included in the URL. My Project is written primarily in PHP. This is a snippit of the code that makes the inital request for an authentication session.
function logOn($mainURL, $credentials)
{
// create a new HTTP_Request object to be used in the login process
$request = new HTTP_Request();
// set the URL of the HTTP_Request object to the family search identity/login endpoint
$request->setUrl("https://web-service/authentication/path?response_type=code&client_id=".$credentials['key']."&redirect_uri=https://www.myredirectPage.edu/");
$request->_useBrackets = false;
$request->addHeader("User-Agent", $credentials['agent']);
$request->addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
$request->sendRequest();
//HTML_HEADER;
//the response will come in the form of an html file
$responseHtml = $request->getResponseBody();
//Dynamically load html from request body onto the browser to allow for authentication
echo $responseHtml;
return $credentials;
}
The end user will enter their login credentials using the loaded html components and hit submit. The web service then redirects to my redirect authentication page. The code there is provided below.
<?php
// process client request (Via url)
//gather code parameters from the redirect url.
if (isset($_GET['code']))
{
echo $_GET['code'];
}
else
{
echo "code not returned";
}
if (isset($_GET['error']))
{
echo $_GET['error'];
}
else
{
echo "error not returned";
}
?>
Thanks in advance to any help with this.

When I use Google Chrome's Network debugger tool, I saw that my project was making unexpected searches for Javascript and Css resources, all resulting in 404 (not found) errors. Upon closer inspection, I could see that the resources were relative paths to resources that are on the web service server. Rather than looking for 'https://webService.net/js/importantJavascript.js' (an existing file located on the service's web server), it was trying to find 'https://mywebpage.edu/js/importantJavascript.js'(a path to a file that doesn't exist).

Related

Manage Sign with Apple redirect in PHP

I'm trying to implement Sign In with Apple workflow on a backend server, for all those devices that do not support it natively.
I've tried both with and without 3rd party libraries. Right now I'm using patrickbussmann/oauth2-apple.
I successfully authorize the account through the authorization URL, but the redirect URL have no fields (especially the 'code' one).
This is how I generate the authorization URL:
function get_apple_signin_url() {
$options = [
'scope' => ['email'],
];
$authUrl = $this->provider->getAuthorizationUrl($options);
$_SESSION['oauth2state'] = $this->provider->getState();
return '{"url": "'.$authUrl.'"}';
}
The URL obtained is correct and it works utill the end of login:
https://appleid.apple.com/auth/authorize?scope=email&state=a9583c14408af68ac05cbfed3a8274ef&response_type=code&approval_prompt=auto&redirect_uri=MY_REDIRECT_URI&client_id=MY_CLIENT_ID&response_mode=form_post
This is the code inside the redirect uri (apple_auth_redirect.php):
<?php
if (isset($_POST['code'])) {
$code = urlencode($_POST['code']);
header("Location: intent://callback?apple_id_token=".$code);
} else {
echo "no_code";
}
As you can see from the authorization URL, the response_mode is form_post. If I use query as response_mode I obtain the code, but I cannot insert email as scope. More details in response_mode at Incorporating Sign in with Apple into Other Platforms (developer.apple.com).
This is the current authorization workflow I've implemented:
Mobile app calls get_apple_signin_url on the server.
Mobile app opens the url in the browser.
The authorization through Apple website is completed and the browser is redirected to redirect uri apple_auth_redirect.php.
The code should be parsed by apple_auth_redirect.php but the redirect request has no fields.
I've implemented the same procedure for Google and Huawei sign in without problems.
I solved the problem. I thought that I wasn't correctly handling the redirect. However, the problem was that I wrote redirect_uri=MY_REDIRECT_URI without "www", just the domain e.g., "my_domain.com". With "www" e.g., "www.my_domain.com", it worked.

Yii2 - Do a http form POST on external URL and redirect to it

I have an application on Yii2.
I have an external vendor i want to redirect. For example, i am encrypting the current user info, and want to send that to the external vendor, so the user information is automatically populated on his website.
Everything works fine if i do that on the front end side using JS.
The problem i have is only my app server is whitelisted to the vendor. So i need to make the redirection happen on the backend.
I tried several method, and even with Guzzle HTTP, and it doesn't redirect.
TO be clear, i am not looking for a simple redirect, it is a form post on external URL.
I went though this post, but the problem remain the same...
Yii2 how to send form request to external url
Does anybody faced this issue?
If I understand you correctly, you want to POST data received from your frontend to the server of a third party company (let's call them ACME). Your webserver is whitelisted by ACME but your clients are not (which is good). You want to show a page on your server and not a page on the ACME server after the POST, right?
You have to send the data with a separate request from your server to the ACME server. You cannot create a HTML <form> and put the ACME server in the action parameter of it, because the request would be sent from the client and not your backend, failing at the whitelist. After you validate your client input, you can send it with guzzle to ACME.
With the status code you can decide if your request was successful or not. You can read more about guzzle here
The code sample below shows how you could POST the $payload (a fictional blog post if you will) as JSON to the ACME server and output a line with the request result.
$payload = [
'username' => 'john.doe',
'postContent' => 'Hello world',
];
$client = new GuzzleHttp\Client();
$response = $client->post('https://acme.example.org/endpoint',['http_errors' => false, 'json' => $payload]);
if($response->getStatusCode() === 200){
echo "Request OK";
}else{
echo "Request failed with status ".$response->getStatusCode();
}

CakePHP REST + AngularJS - How to send Access Denied response in JSON?

I am new to CakePHP and am using version 2.7.5.
I followed the tutorial to create a basic REST service.
I now secured them using the basic auth tutorial.
Now, I have an AngularJS app over this REST service but need a way to prompt users to login or say their account does not have access to that resource.
Right now, when the REST call is made, and they do not have access, the response is a redirect HTML page to "/" or to logon. But I want the response in JSON with a message that says "access denied" or "session is up please logon.." etc.
I know it's the flash variable in cakephp but i am using AngularJS.
So my question is, where do I code in cakephp to send json response instead of HTML page redirect if a user does not have access to a certain rest url after logging in?
You can just return a response header back to the request with the correct status code(401).
if(!$authorized){
return header('HTTP/1.0 401 Unauthorized');
}
You can catch the error code in your request method, for example an ajax request
.error(status){
switch(status.code)
{
case 401:
//Unauthorized
break;
}
}

Automatic Soundcloud PHP Api authentication without user interaction

In my application i want to use the Soundcloud API with my own Soundcloud user. The Soundcloud API authentication process involves a user being redirected to the Soundcloud homepage, login and authorize the application, so that the page can use the API for this user.
I want to automate the whole process, because my own user is the only user which gets authenticated. Is that possible?
Here is my code so far:
$soundcloud = new \Services_Soundcloud(
'**',
'**',
'http://**'
);
$authorizeUrl = $soundcloud->getAuthorizeUrl();
$accessToken = $soundcloud->accessToken();
try {
$me = json_decode($soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
But the line $accessToken = $soundcloud->accessToken(); throws an exception:
The requested URL responded with HTTP code 401.
500 Internal Server Error - Services_Soundcloud_Invalid_Http_Response_Code_Exception
Hi All,
Here I am going to share my experience with Soundcloud API (PHP)
See my Question: Link
Recently I started to work with Sound cloud API (PHP) and I decided to use PHP API by
https://github.com/mptre/php-soundcloud.
But When I was trying to get access token from Sound cloud server by this code:
// Get access token
try {
$accessToken = $soundcloud->accessToken($_GET['code']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
I had check the $_GET['code'] value. But strange there is nothing in
$_GET['code'] this is blank. The Soundcloud was returning "The
requested URL responded with HTTP code 0" error. That time I was
testing Soundcloud on WAMP Localhost.
Allot of Goggling I found a solution to fix "The requested URL
responded with HTTP code 0" issue. I had download 'cacert.pem' file
and put inside our demo project folder (inside Services/Soundcloud/).
Then after I added some code in 'class Services_Soundcloud'
function protected function _request($url, $curlOptions = array()).
// My code in side function
$curlPath = realpath(getcwd().'\Services\cacert.pem');
$curlSSLSertificate = str_replace("\\", DIRECTORY_SEPARATOR, $curlPath);
curl_setopt($ch, CURLOPT_CAINFO, $curlSSLSertificate);
Saved 'class Services_Soundcloud' file and moved on live server. After
move my project from WAMP to Live server I start to check it again.
When I open my index.php it's ask me to login
I use my Facebook account to login.
after login it was asking to connect with Soundcloud
after connect everything working smooth, I got my info with
$me = json_decode($soundcloud->get('me'));
but a new problem start to occurring which was that my access token
being expire again and again. Then I use session :D
// code for access token
$code = $_GET['code'];
// Get access token
try {
if(!isset($_SESSION['token'])){
$accessToken = $soundcloud->accessToken($code);
$_SESSION['token'] = $accessToken['access_token'];
}else{
$soundcloud->setAccessToken($_SESSION['token']);
}
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
And now everything working awesome. i can get all my details, tracks everything from SC server
Hope it will help you to fight with Soundcloud API Cheers!!!! :)
I'm looking for the same thing, but according to the soundcloud's api (check the Authenticating without the SoundCloud Connect Screen paragraph):
// this example is not supported by the PHP SDK
..and is not supported by the Javascript neither.
I've tryed to auth with python:
# create client object with app and user credentials
client = soundcloud.Client(client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
username='YOUR_USERNAME',
password='YOUR_PASSWORD')
..then the uploading python method:
# upload audio file
track = client.post('/tracks', track={
'title': 'This is my sound',
'asset_data': open('file.mp3', 'rb')
})
and it works just fine.
So, for now, you have 2 ways:
Use another language, Python or Ruby (the only 2 sdk that actually support this feature) or use a small python/ruby script as a bridge for this particular need;
Add this funcionaliy to the PHP SDK (i'm trying to do it quick'n'dirty, if i get success, i'll share ;)
There is no magic behind its implementation in Python and Ruby SDK's.
What's happening is that POST request is sent to http://api.soundcloud.com/oauth2/token with the following params:
client_id='YOUR_CLIENT_ID'
client_secret='YOUR_CLIENT_SECRET'
username='YOUR_USERNAME'
password='YOUR_PASSWORD'
And Content-Type: application/x-www-form-urlencoded
The response body contains access_token, that can be used for the further authorization of your requests. Thus, your GET request to /me endpoint will look like: /me?oauth_token=YOUR_ACCESS_TOKEN&client_id=YOUR_CLIENT_ID. (I believe, client_id is redundant here but all their apps keep adding it).
Here is the Postman Doc I created for demonstration: https://documenter.getpostman.com/view/3651572/soundcloud/7TT5oD9

JavaScript widget with trust based authentication under active directory

I'm building a new project and I'm having some debate over how it needs to be developed. The big picture is to develop a consumable JavaScript widget that other internal developers can embed into their web applications. The trick is that the consumer needs to be able to tell me what AD user is currently logged into their page...and then I need to trust that the passed username is coming from the consumer and hasn't been tampered with via outside sources.
The overall solution needs to have a VERY simple set-up on the consuming side involving no compiled code changes. Also it needs to be functional across both ASP.net and PHP applications (hence my decision to go with JavaScript).
Overall, it's kind of like an Oauth solution...except the trust between domains can be intrinsic since I'll already know every user in the company trusts the host domain.
I started stubbing it out and got kind of stuck. My idea was that I would basically host a JavaScript file that the client host could embed in their page. During their page load cycle, they could init my JavaScript widget and pass it a plain text username (all I really need). Somehow I would establish an secure trust between the client host's web page, and my widget so that it would be impossible for a third-party to embed my widget into a false web page and send action commands under a user other than their own.
I hope this makes sense to someone.
I haven't really discovered an answer so to speak, but I've decided on a method:
So, I decided on a pattern where I write my JavaScript and HTML widget using the proposed jQuery UI Widget Factory. That allows the my consumer to implement the widget using simple syntax like:
<script src="widget.js"></script>
$('#someElement').myWidget({ encryptionUrl: handlerPath });
Now, you'll noticed that as part of my widget, I ask the consumer to pass a "handlerPath." The "handler" is simply an Microsoft MVC Controller which is in charge of getting the logged in user, and encrypting the call.
So the handler in my app looks something like this...
[Authorize]
public JsonpResult GetToken(string body, string title, string sender)
{
Packet token = new Packet();
try
{
// Get the widget host's public cert
string publicKey = "some.ssl.key.name.here";
// Get the consumer host's private cert
string privateKey = "this.consumers.ssl.key.name.here";
// Build a simple message object containing secure details
// Specifically, the Body will have action items (in JSON) from my widget
// The User will be generated from the consumer's backend, thus secure
Message message = new Message(){
Body = body,
Title = title,
User = System.Web.HttpContext.Current.User.Identity.Name,
EncryptionServerIP = Request.UserHostAddress,
Sender = new Uri(sender),
EncryptionTime = DateTime.Now
};
PacketEncryption encryption = new PacketEncryption();
// This class just wraps basic encryption and signing methods
token = encryption.EncryptAndSign(message, publicKey, privateKey);
token.Trust = "thisConsumerTrustName";
}
catch (Exception exception)
{
throw;
}
return this.Jsonp(token);
}
Now, I have an encrypted "token" which has been encrypted using the widget host's public key, and signed using the widget consumer's private key. This "token" is passed back to the widget via JSONP from the consuming server.
My widget then sends this "token" (still as JSONP) to it's host server. The widget hosting server has decrypting logic which looks something like this.
public Message DecryptAndVerify(Packet packet, string requestIP)
{
if (packet == null) throw new ArgumentNullException("packet");
if (requestIP == null) throw new ArgumentNullException("requestIP");
Message message = new Message();
try
{
// Decrypt using the widget host's private key
RSAEncryption decrypto = new RSAEncryption("MyPrivateKey");
// Verify the signature using the "trust's" public key
// This is important because like you'll notice, I get the trust name
// from the encrypted packet. I then maintain a "trust store" mapping
// in my web.config, or SQL server
RSAEncryption verifyo = new RSAEncryption(GetPublicKeyFromTrust(packet.Trust));
string decryptedJson = decrypto.DecryptString(packet.EncryptedData);
// Verify the signature
if (!verifyo.Verify(decryptedJson, packet.Signature))
{
Exception ex = new Exception("Secure packet was not verified. Tamper evident");
throw ex;
}
// If the message is encrypted correctly, turn it into a message object
message = decryptedJson.FromJson<Message>();
// Verify the ip
if (message.EncryptionServerIP != requestIP)
{
Exception ex = new Exception("Request IP does not match encryption IP. Tamper evident");
throw ex;
}
// Verify the time
if ((DateTime.Now - message.EncryptionTime).Seconds > 30)
{
Exception ex = new Exception("Secure packet is too old");
throw ex;
}
}
catch (Exception ex)
{
throw ex;
}
return message;
}
The idea is that the JavaScript widget determines the secure actions the end user wants to take. Then it calls back to it's host (using the handler path provided by the consumer) and requests an encrypted token. That token contains the IP address of the caller, a timestamp, the current AD username, and a bundle of actions to be completed. Once the widget receives the token, it passes it over to it's own host server at which point the server checks to make sure that it is
Signed and encrypted properly according to predefined trusts
Not older than 30 seconds
From the same IP as the initial request to the consumer's server
After I determine those checks to be valid I can act on the user's actions by creating a WindowsPrincipal identity from the string username like this:
WindowsPrincipal pFoo = new WindowsPrincipal(new WindowsIdentity("username"));
bool test = pFoo.IsInRole("some role");
All said and done, I have established a trusted request from the widget consumer, and I no longer have to prompt for authentication.
Hopefully this helps you out. It's been running in my internal environment for about a month of QA and it's it's working great so far.

Categories