Change HTTP request authorisation header with PHP or HTML - php

The quick question is: is there ane way to change http authorisation header with html / php / javascript?
The goal
I'd like to make an auth service used for user login as well as providing with whole site protection. I want user to be restricted from viewing any file except login page unless authorised. For php I can of course check at the beginning for example session token availability, and redirect if missing, but I can't do it directly for for example jpg images. I thought of creating htaccess file that will verify if user is logged.
The solution
1.
Using Apache I've created .htaccess file, that verifies, if HTTP authorisation is set. If not it redirects any request to login page. With that solution one can not open any file (no matter if it is php script or for example jpg image) except of the login page:
RewriteCond %{HTTP:Authorization} ^$
RewriteCond %{REQUEST_URI} !^/login.php
RewriteRule .* /login.php [L,R]
2.
The login page should display form and when login and password are correct set the http request auth header with proper token.
Unfortunately I can't find a way to create manually http request auth header. The only way I found was to use basic auth:
$auth = new Auth();
if (!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SESSION)) {
$auth->logout();
}
if (!empty($_SERVER['PHP_AUTH_USER']) && empty($_SESSION)) {
$login = $_SERVER['PHP_AUTH_USER'];
$haslo = (!empty($_SERVER['PHP_AUTH_PW']) ? Auth::hashPassword($_SERVER['PHP_AUTH_PW']) : null);
$auth->login($login, $haslo);
}
$auth->getLoginForm();
Where getLoginForm() displays Basic Auth standard form
public function getLoginForm()
{
header(self::HEADER_ERROR_ASK_CLIENT_DATA);
header(self::HEADER_RESPONSE_401);
exit;
}
This solution works, but http request auth header holds the original login data all the time, which is what I want to avoid. I want to inject there "Bearer + token" string, which will help in securing whole system.
What I've tried
I can easily do that with external frontend. For example with windows desktop app I can send one request with basic auth header and the next with bearer header.
The same I can do with JQuery and AJAX - I can retrieve token using url with basic auth, and then use token with custom header for next requests.
I can also make different requests with PHP CURL.
But I can't find a way to force regular browser to login with Basic auth header and after success keep new, custom bearer header for next requests.

There is no standard mechanism to get a User Agent (browser) to provide an Authorization: Bearer header by itself.
What you can do:
make sure all your requests are done via XHR (Ajax), and send the header there. But this will not allow "regular" file loads (new pages, images, scripts, CSS...).
what most people do: send a cookie with your authentication token, and check for that cookie. The browser will automatically send the cookie.
As an aside, note that your .htaccess only checks that there is an Authorization header present, not its value, so it's quite useless. You want to channel all reads via a script that will actually verify the header or cookie before delivering the file.

Related

Redirect with HTTP 403

I'm using Slim PHP and want to redirect the user to /login if they are not logged in but try to access a page that requires a user to be logged in. When searching for how to build my middleware, I find variations of this code all over the place
class Auth{
public function requireLogin(Request $request, Response $response, $next){
if( !isLoggedIn() ) return $response->withRedirect('/login', 403);
return $next($request, $response);
}
}
for example in this SO answer and this Slim discourse answer.
The problem is that I can't get the combination of redirecting and HTTP 403 to work. From what I can tell, normal HTTP redirects are restricted to the HTTP codes 3xx. Indeed, the above code works fine when used with for example 302.
Am I missing something, or are all the answers that combine withRedirect and 403 "incorrect" (as in not causing an actual redirect of the users browser)?
If your application is an HTML website that's accessed using a web browser, then the browser will only redirect if the status code is a 3xx one.
If your application is an API that's accessed using an HTTP client then you have more leeway. For an API, you'd use a 403 or 401 status code to indicate that the request cannot be fulfilled without authorisation. You may also include a Location header to tell the client where to go to get authorisation, but of course it's up to the client if they follow up on that link.

Slim3 redirect GET request as POST request

Just started learning Slim3. Have been spending some time figuring out how to perform redirects with overriding original request type with no success.
I want the /origin route to perform the redirect to /dest route.
/origin route receives GET request performs validation and after success redirects with POST request to /dest uri route. Here is the screenshot. I think I am doing something dumb here:
$app->get('/origin', function($req,$res,$args)
{
$req= $req->withHeader('X-Http-Method-Override','POST');
return $res->withRedirect('/dest');
});
$app->post('/dest', function($req,$res,$args)
{
echo "this is destination page";
});
As noted in the comment, this is not possible as the request made by the browser is not in your control.
When you call ->withRedirect() you are sending a status code of 302 and a Location header to the HTTP client (web browser usually).
The web browser sees the 302 status code and then issues a new request to the URL in the Location header. The server has no control over this request and every web browser makes a GET request.
Now, if you want to redirect a POST request to another URL and keep the same POST method, then you can use the 307 status code with a Location header and the browser should do the right thing. Note that this code does not let you change a GET into a POST - it just keeps the same method as the original request for the followup redirection request.

Google drive api file_get_contents and refferer

I am trying to list files from google drive folder.
If I use jquery I can successfully get my results:
var url = "https://www.googleapis.com/drive/v3/files?q='" + FOLDER_ID + "'+in+parents&key=" + API_KEY;
$.ajax({
url: url,
dataType: "jsonp"
}).done(function(response) {
//I get my results successfully
});
However I would like to get this results with php, but when I run this:
$url = 'https://www.googleapis.com/drive/v3/files?q='.$FOLDER_ID.'+in+parents&key='.$API_KEY;
$content = file_get_contents($url);
$response = json_decode($content, true);
echo json_encode($response);
exit;
I get an error:
file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
If I run this in browser:
https://www.googleapis.com/drive/v3/files?q={FOLDER_ID}+in+parents&key={API_KEY}
I get:
The request did not specify any referer. Please ensure that the client is sending referer or use the API Console to remove the referer restrictions.
I have set up referrers for my website and localhost in google developers console.
Can someone explain me what is the difference between jquery and php call and why does php call fails?
It's either the headers or the cookies.
When you conduct the request using jQuery, the user agent, IP and extra headers of the user are sent to Google, as well as the user's cookies (which allow the user to stay logged in). When you do it using PHP this data is missing because you, the server, becomes the one who sends the data, not the user, nor the user's browser.
It might be that Google blocks requests with invalid user-agents as a first line of defense, or that you need to be logged in.
Try conducting the same jQuery AJAX request while you're logged out. If it didn't work, you know your problem.
Otherwise, you need to alter the headers. Take a look at this: PHP file_get_contents() and setting request headers. Of course, you'll need to do some trial-and-error to figure out which missing header allows the request to go through.
Regarding the referrer, jQuery works because the referrer header is set as the page you're currently on. When you go to the page directly there's no referrer header. PHP requests made using file_get_contents have no referrer because it doesn't make much sense for them to have any.

How to use get_file_contents in PHP when authorization is needed for URI?

I'm making a request to retrieve a JSON file to a server at a particular secure DocuSign uri. However, unless I put in the authorization information (which I do have), I am unable to have the file returned.
<?php
$json = file_get_contents("https://example.docusign.com/sensitiveIDs/moreID");
echo $json
?>
Where would I put in authorization information for the specific server/username/password/other info needed to access the particular DocuSign server using a method like this in PHP? Is there a better method to use for this scenario in PHP?
It depends on how the authorization is implemented. If its basic or digest HTTP authentication then specify it in the URL:
file_get_contents("https://$USER:$PASSWORD#example.docusign.com/sensitiveIDs/moreID");
Cookie based authentication is a lot more difficult (and probably easier to use Curl or even a more complex system like Guzzle. If its oauth2, then you probably want an oauth2 library.
Your call needs to include authentication to make the GET call to retrieve the file.
If your app is initiated by a human use Oauth to retrieve access and refresh tokens. Then included the access token with the GET request.
If your app is a "system app" that wants to autonomously retrieve the file, then you should authenticate by using X-DocuSign-Authentication -- include the following header in your HTTPS request. Since the request is HTTPS, the content is encrypted on the wire:
X-DocuSign-Authentication: <DocuSignCredentials><Username>{name}</Username><Password>{password}</Password><IntegratorKey>{integrator_key}</IntegratorKey></DocuSignCredentials>
Replace {name} with your email address (no braces), etc.
The bottom line is that you can't use the file_get_contents Php method. Instead, you'd do something like the following:
Use https://github.com/rmccue/Requests or a similar library to help with the https request. (http is not allowed due to security issues.)
(untested code)
$url = $base_url . $the_url_section_for_this_call
$headers = array('X-DocuSign-Authentication' =>
'<DocuSignCredentials><Username>your_name</Username><Password>your_password</Password><IntegratorKey>your_integrator_key</IntegratorKey></DocuSignCredentials>');
$request = Requests::get($url, $headers);
# Check that the call succeeded (either 200 or 201 depending on the method
$status_code = $request->status_code;
if ($status_code != 200 && $status_code != 201) {
throw new Exception('Problem while calling DocuSign');
}
$json = $request->body;

PHP Twitter proxy that supports XAuth on an Apache server

I've been banging my head against this problem for nearly two days now, and I'm hoping someone on this site can help me.
I live in China and have a server (shared hosting) located in Hong Kong. I've set up a PHP Twitter proxy on the server, and I connect to the proxy using Twitter for iPhone (AKA Tweetie). It's worked beautifully for the past year or so.
Twitter for iPhone was updated yesterday and now requires XAuth authorization to connect to twitter.com (previously, it used Basic Auth). Since the update, I haven't been able to authenticate myself using my proxy, in spite of making (what I believe to be) the appropriate changes to my proxy.
Conceptually, this isn't a very difficult problem to crack. In order to authenticate with twitter.com using XAuth, an app must send a POST request to https://api.twitter.com/oauth/access_token. The POST body must be of the form:
x_auth_username=aUserName&x_auth_mode=client_auth&x_auth_password=aPassword
Additionally, the POST request must have an Authorization header in the form:
OAuth oauth_signature_method="HMAC-SHA1", oauth_consumer_key="IQKbtAYlXsomeLGkey0HUA", oauth_nonce="8B265865-3F57-44FF-BCD6-E009EA7D4615", oauth_signature="sbwblaho64blahr934mZQ+23DYQ=", oauth_timestamp="1277356846", oauth_version="1.0"
So, what I've done is used .htaccess to copy the Auth header to a $_REQUEST variable using this code:
RewriteCond %{HTTP:Authorization} ^OAuth.*
RewriteRule (.*) index.php?OAuth=%{HTTP:Authorization} [QSA,L]
My proxy copies the contents of that $_REQUEST variable to an instance variable called $self->oauthHeader. Then, I make add it as a header to my cURL request using the following code:
if (isset($this->oauthHeader)) {
$headers[] = 'Authorization: '.$this->oauthHeader;
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$curl_options[CURLOPT_HTTPHEADER] = $headers;
}
I also add the original request's POST body to the cURL's POST body using:
$curl_options[CURLOPT_POST] = true;
$curl_options[CURLOPT_POSTFIELDS] = #file_get_contents("php://input");
I send the cURL request to Twitter. Everything seems to work correctly, but I inevitably receive a response of "Failed to validate oauth signature and token."
I'm at my wit's end, and I can't for the life of me think what I'm doing wrong. Any help would be much appreciated.
You can use this alternative solution, for jailbroken iOS devices only: http://code.google.com/p/gfwinterceptor/

Categories