Jump to content

Module: RestApi


thomasaull

Recommended Posts

@pmichaelis If the error is thrown in line 131 it's likeley there is an error with the JWT Authorization. Maybe the Token you're submitting is not valid, maybe something else. Hard to tell with the little information you provided.

Oh, just noticed you already mentioned the JWT Auth… ? Probably the error is produced in those 4 lines:

$secret = wire('modules')->RestApi->jwtSecret;
$token = str_replace('Bearer', '', $authHeader);
$token = trim($token);
$decoded = JWT::decode($token, wire('modules')->RestApi->jwtSecret, array('HS256'));

if the secret is in your config and you didn't change it, I'd check if the token gets transmitted properly with the request.

Link to comment
Share on other sites

5 hours ago, thomasaull said:

@pmichaelis If the error is thrown in line 131 it's likeley there is an error with the JWT Authorization. Maybe the Token you're submitting is not valid, maybe something else. Hard to tell with the little information you provided.

@thomasaull It seems that the authorisation headers are not present.

Added the following line to the htaccess:

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

auth headers are stored in following variable

$_SERVER['REDIRECT_HTTP_AUTHORIZATION'];

Please don't ask why.

Link to comment
Share on other sites

  • 2 months later...
On 2/28/2019 at 3:17 PM, eelkenet said:

Here is the final cleaned-up and more secure 'api' template that I am using in between the RestApi router and ProCache, perhaps it can be of some help:

 

I ran into issues with a slow server using this method, where wireHttp would already resolve a result while RestApi was still running.
So with help from my co-worker @harmvandeven we came up with a more stable version, with some more redundancy: 
 

<?php

/*

    api.php, a simple PW template to fill the gap between the RestApi and ProCache modules
    v2

    @author: @eelkenet, with help from @harmvandeven & @ryan

    1. Create a template called 'api' and set it up using the following settings:
    - Allow URL segments
    - Allow guests to view the page
    - Set the Content-Type to application/json
    - Make sure to NOT Prepend or Append any files

    2. Add a page using this template and allow ProCache to run its magic

*/

$timeout = 600;
$maxAttempts = 10;

// Pre-check for unwanted symbols
if (strpos($input->urlSegmentStr(), '.') !== false) {
    throw new Wire404Exception();
}

// Build request URL
$endpoint = $modules->get("RestApi")->endpoint;
$url = $input->scheme() . "://" . $config->httpHost . "/" . $endpoint ."/" . $input->urlSegmentStr();

$http = new WireHttp();

// Set a high timeout, to deal with a slow server
$http->setTimeout($timeout);

// Get the HTTP status of the page, to make sure it exists in the first place
$status = $http->status($url);

// If the page exists, or possibly redirects to valid content
if ($status >= 200 && $status < 400) {

    $result = false;
    $attempt = 0;

    // If the result isn't a string, something went wrong
    while(gettype($result) !== "string" && $attempt++ < $maxAttempts) {

        $result = $http->get($url);
        if ($attempt > 1) wire()->log->message("Loading content at $url, attempt $attempt: " . gettype($result));
    }

    // Double check if the data is a string..
    if (gettype($result) === "string"){

        // .. And check if it can be decoded, if so: return the data and thus cache it
        if (json_decode($result) !== NULL) return $result;

        // If it cannot be decoded: throw exception (don't cache it)
        throw new WireException("Found the data at $url, but it could not be decoded. Please check your API output!");
    }

    // Throw exception if data could not be loaded in time (don't cache it)
    throw new WireException("Found the data at $url, but could not load it in time, after $attempt attempts. Result has type: " . gettype($result));

}

// Throw generic exception if the requested page was not found or there was another error
throw new WireException("Failed to load the content at: $url, with HTTP status: " . $status);

 

 

 

  • Like 4
Link to comment
Share on other sites

Hi

I've just installed this module (processwire version 3.0.123) but I can't get anything off a connection. I tried a clean install without any modules activated and have the some problem. Is there anything that has to be installed to be able to get a response? I'm developing on a local environment of xampp and tried it on a mac os environment with mamp aswell.

I tested it on a production environment (online hosting) and there it is working. I'm guessing it has something to do with the local servers. Anybody has an idea what should be activated?

Thanks in advance

Link to comment
Share on other sites

@thibaultvdb It's a bit difficult to help from here. One thing you could try is to go through the code in Router.php and return or exit early to find out until where the code runs. The main functions are "go()" and "handle()". Another idea is to compare php settings between your hosted and local environment with "phpinfo()". If you can isolate the issue it's much easier to help.

  • Like 1
Link to comment
Share on other sites

13 hours ago, thomasaull said:

@thibaultvdb It's a bit difficult to help from here. One thing you could try is to go through the code in Router.php and return or exit early to find out until where the code runs. The main functions are "go()" and "handle()". Another idea is to compare php settings between your hosted and local environment with "phpinfo()". If you can isolate the issue it's much easier to help.

The main functions are all going like they should. I tried comparing the php info like you said but those files are huge so hard to compare them and find out what is missing/wrong. Is there a localhost software you recommend that is working? Friends that have mamp pro don't have the issue but using mamp/xampp does give me the 404. It's strange that I don't get errors, only a 404 page.

If I can provide you anything please let me know since serverside issue's aren't my best area of working.

Link to comment
Share on other sites

@thibaultvdb 

I think that by default on XAMPP your ProcessWire installation is in a subdir, and I bet that the module is giving you as api endpoint something like : /subdir/api instead of the /api endpoint. 

You should ask your friends to help you to setup your localhost environment to use a domain like  http://mylocalwebsite.local

To get started, you can follow the second answer here https://stackoverflow.com/questions/16229126/using-domain-name-instead-of-localhost-in-with-https-in-xampp

or follow this tutorial to use AcrylicDNS (the best solution IMO, do not be afraid, it's really easy to setup) https://www.ottorask.com/blog/automated-apache-virtual-hosts-on-windows/

 

Good luck.

  • Like 3
Link to comment
Share on other sites

@flydev I must say you are the savior of the day. The reason was indeed that xampp is putting "localhost" in front of the site url.
In my case this was "localhost/sitename" the RestApi module probably didn't understand this sitename url what gave me 404-pages all the time.

@thomasaull You mentioned that maybe this could be fixed through the settings of the module. Could you give an example of a path?
Maybe it's usefull to add a option to the module or something that notifies the user if it is using localhost or to automatically prefix this with localhost? I don't think I will be the only one that uses the localhost prefix ? 

Thanks for the help already! Hopefully there is a possibility to handle this in the settings so I don't have to use these virtual hosts. Or maybe look at the processwire config? The processwire handles this localhost prefix perfectly.

Link to comment
Share on other sites

@thibaultvdb I need to check this, since I think (when I remember it properly) I put this option in specifically for this use-case. If you want to fiddle around try making it work or you know/want to figure out how ProcessWire does this automatically feel free ? Otherwise I can't really make any promise when I'm going to be able to look into this

Link to comment
Share on other sites

  • 1 month later...

@Hurme

Did you check your server error logs for hints? Or site/assets/logs/ ?

First of all, you could try to delete everything in site/assets/cache/modules/. 

If that doesn't work, rename the REST API module: prepend a dot (.modulename).

Link to comment
Share on other sites

@dragan Hi, I've left the office and wont be back until next week, but I'll see if deleting the cache has any effect. There were no errors in the log files, just your usual "Saved module X". Of course deleting the module itself resolves the crashing issue, but then you can't really use the module.

Link to comment
Share on other sites

  • 4 weeks later...

Recently a user of this module had the problem that some multi-language fields weren't working correctly.kno After some investigation I discovered, that the hook this module uses (it's a "before ProcessPageView::execute") kicks in to early for the multi-language plugins to be ready. Does anyone knows of a hook, which can do something similar (basically take over the default routing of ProcessWire) while still have the other modules loaded?

One alternative approach for this specific problem would be to not trigger the module via a hook but with an own template and page like the old RestApiProfile did. A couple of benefits would come for free aswell (these are my assumptions, not tested yet):

  • ProCache should work without any workarounds
  • Multi-Language works
  • Websites in subdirectories (if working in ProcessWire in general) should work
  • site profile export would work if the /api folder lives in /templates by default

Any potential downsides I'm not seeing yet? Thoughts?

Link to comment
Share on other sites

I wrote an api-module a few years ago, where the module generated a custom template (e.g. "api-page"), which could be used to create one or more endpoint-pages. To handle calls to these pages I used ProcessPageView::pageNotFound like @bernhard did:

$this->addHookBefore('ProcessPageView::pageNotFound', $this, 'handleApiRequest');
public function handleApiRequest(HookEvent $e) {
	$page = $e->arguments[0];

	if ($page->template === 'api-page') {
		// handle request here...
		$otherEvent = $e->arguments(0); // grab event provided to PageRender::renderPage
		$e->replace = true; // prevent PageRender::renderPage from being called
	}
}

It worked nice for me, but I cannot say if caching or multi-language works better in this hook. pageNotFound should be called later than execute, so there is a chance that it helps ?‍♂️

 
  • Like 4
Link to comment
Share on other sites

  • 2 weeks later...

Hello everyone,
while building an app-interface for a page, I developed some changes and improvements to this module, which I made available as a pull request
But @thomasaull and I are not quite sure if it makes sense to transfer these basic changes into the main module as well. Therefore we would like to hear your opinion: What do you think of the new module version? Which features would be useful for you? 

I have developed several new features that allow the administration of Api accesses via the ProcessWire backend. I also revised the authentication and added a new Double-JWT option that works with long-lasting refresh and short-lived access-tokens.

New Features:

  • New menu item "Restapi" in the ProcessWire menu under "setup
  • Management of Api accesses (applications) outsourced to the new menu item
  • Apikeys now authorize api-access
  • Creation of multiple applications with different auth types possible
  • Double-JWT Authentication, renewable tokens
  • token-sessions can be viewed and deleted in the backend
  • Improved exception handling: Each endpoint can throw exceptions, which are then output with the appropriate HTTP status header and message.
  • Like 10
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...