thomasaull

Module: RestApi

Recommended Posts

Some time ago I created a site profile for creation of a REST API with ProcessWire. Since I kept struggeling with updating stuff between different projects which use this, I decided to convert it into a module. It is now ready for testing: https://github.com/thomasaull/RestApi

Additionally I added a few small features:

  • automatic creation of JWT Secret at module install
  • routes can be flagged as auth: false, which makes them publicly accessible even though JWT Auth is activated in module settings

To check things out, download and install the module and check the folder /site/api for examples.

If you find any bugs or can think of improvements, please let me know!

  • Like 14

Share this post


Link to post
Share on other sites

@nicolant had some problems to get the old site profile working with different domains for api and client:

It should work out of the box with the module, but apparently you need to add an OPTIONS route for every endpoint. I could automate this, but don't know if it's a good idea to do this for every route, since I'm not an expert on this  CORS / preflight. Opinions?

Share this post


Link to post
Share on other sites

Great, have to try this soon. Thanks for sharing!

Just flew over the readme and saw that you are always using http instead of https in your instructions. Is that a typo? Or does it also work with http? Maybe a hint that https would be more secure would make sense?

No idea how JWT Auth works and I also didn't have a look at your examples yet. Just wanted to say thank you, follow the thread and maybe my comment is even useful 🙂

Share this post


Link to post
Share on other sites

Thanks @bernhard! The API does not really care if it's served over http or https, it's just HTTP(s)-Requests after all. If your server is configured to redirect all http requests to https, it'll do so with these as well. However, it's always a bit of a hazzle to test locally, so I left  the examples as is and put a note that it's a good idea to use https 🙂

JWT Auth (in this case) works like the following:

  1. The client sends a login-request with username + password (this definitely should go over HTTPS)
  2. The server checks the login credentials and if correct, creates a unique token with an added encrypted signature
  3. The client uses this token to authentiate every following request

Since the client does not know the secret, he cannot modify the contents of the token without making it invalid

That's basically how I understood it 😉

  • Like 2

Share this post


Link to post
Share on other sites

I'd like to add that JWT is to be taken with a grain of salt. Once a token is issued there's not way to revoke it's validity unless one is storing something in the db to validate the jwt against. Having something stored on the server makes it essentially a more complex, more manual session handling, so there's at least in my opinion no longer a point to use JWTs. They're mostly useful for shortlived tokens or you can use them if you implement something like oauth or similar stuff. I personally wouldn't suggest using them like they're implemented currently in the module.

  • Like 2

Share this post


Link to post
Share on other sites

Thanks for your input @LostKobrakai , that's exactely why I put this up, since it's a security sensitive topic.

Again I'm not an expert on JWT, but I thought that's what the „exp" Parameter is for? In the module it's set to the "sessionExpireSeconds" of PWs config (which is 24h I think). I made a quick test and set it to 2 minutes and while it worked at first after a couple of minutes I got an Error: "Error: Exception: Expired token".

So I guess you're right, there is no way to revoke its validity but on the other hand it seems like it's not valid forever (at least if you don't set it to be)

Share this post


Link to post
Share on other sites

It's certainly not valid forever, but once a token is compromised there's no way to just invalidate that single token before it's going to expire on it's own. By using plain old sessions you have the ability to do so. And depending on the context 24h can be quite a long time. 

Share this post


Link to post
Share on other sites

Absolutely true. So what would be a feasable Alternative then if I don‘t want to use sessions? Say, because of multiple services (where the alternative would be to store alle the user data on every service)

Share this post


Link to post
Share on other sites

Hey Thomas,

Thanks for this module, looks really interesting, and I'm looking forward to giving it a go. Just a quick comment on this part of the README:

Quote

Currently the endpoint for the api is hardcoded to /api. That means a page with the name api is not going to work if you`ve installed this module. I might make the endpoint configurable via module settings in the future.

I think that a configurable endpoint name would definitely be a worthwhile option – or if that turns out to be difficult, perhaps you might want to consider something slightly more descriptive, such as /rest-api/ or something?

To be completely honest I'm being a bit selfish here: I've got the bad habit of using /api/ for any site-specific API implementations I might need, and that would pose an issue for this particular module 😅

Reminds me of the "two hard things in computer science" thing. This thread already covers both: cache (well, token...) invalidation and naming things 🤔

  • Like 2

Share this post


Link to post
Share on other sites

I'd really question why you don't want to use plain old sessions. I mean it doesn't have to be cookie-based even if that's imho still the easiest way to not get bitten by compromised sessions. To give my argumentation a bit more ground work you might want to look into the following blogposts. The latter has a quite simple flow-chart about why JWT just doesn't work well for session authentication.

http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/
http://cryto.net/~joepie91/blog/2016/06/19/stop-using-jwt-for-sessions-part-2-why-your-solution-doesnt-work/

There's also oauth, but that's mostly just another way to obtain a "session" with an service, where you allow a third party to access your content without giving away your credentials.

Share this post


Link to post
Share on other sites

I actually stumbled upon these two articles when I did some resarch on saturday and I think I'm getting your point. However I don't agree with all of the statements made there:

On the flow chart on the far right it says “I'll just use refresh tokens" which he states couldn't be revoked – afaik usually you save the refresh token in the datebase of your Auth Server and everytime a user wants to refresh a token you check if it is still valid. So e.g. you could hand out short lived tokens (like 5-10 minutes) and everytime it expires the client has to obtain a new token via the refresh token if it's not revoked.

In an upcoming project we might have multiple endpoints for different task, where it just sounded good to have an Auth Server which holds all the user information and hands out tokens, which the client uses on the other server to access something. On "Footnote: microservice architectures" of part 2 the autor suggests to use single use tokens to get a session on the other service, which I think means, If I want to revoke a session I need to do it on multiple places right?

Aaaanyway, I did some tests with the API Module, sessions and a cross-origin client and it also works quite well, so with 0.0.3 you can choose your auth method in module settings between none / session / jwt

  • Like 3

Share this post


Link to post
Share on other sites
On 9/25/2018 at 7:00 PM, thomasaull said:

On the flow chart on the far right it says “I'll just use refresh tokens" which he states couldn't be revoked – afaik usually you save the refresh token in the datebase of your Auth Server and everytime a user wants to refresh a token you check if it is still valid. So e.g. you could hand out short lived tokens (like 5-10 minutes) and everytime it expires the client has to obtain a new token via the refresh token if it's not revoked.

As soon as you save anything on your server or in a db you loose the one feature JWTs really have over sessions, the one by which people generally choose JWTs: statelessness. So for a website adding an API for a JS frontend, why go through the length of trying to make JWT auth secure via some refresh token and some db table storing them, when php sessions already bring all you need to do basically the same without the fancy buzzwords and using cookies, which are more save in their handling on the browser side as well. Your argument about duration of authentication vs. refreshing the authentication often is a topic, which is actually totally unrelated to how any authentication prove is stored on the client. Both cookies as well as JWTs cannot be revoked once they're on the client. The difference is that php brings all the server side logic needed for sessions and their revokation, but you need to implement all of that for JWTs, which aren't really meant for stateful authentication in the first place.

On 9/25/2018 at 7:00 PM, thomasaull said:

In an upcoming project we might have multiple endpoints for different task, where it just sounded good to have an Auth Server which holds all the user information and hands out tokens, which the client uses on the other server to access something. On "Footnote: microservice architectures" of part 2 the autor suggests to use single use tokens to get a session on the other service, which I think means, If I want to revoke a session I need to do it on multiple places right?

That sounds like a use-case for oauth.

About your question: If you have multiple servers and you need to (be able to) actively revoke access for some user you need those server(s) to be aware of the revokation. Using client side stored tokens alone you just cannot revoke validity. Your server(s) could always ask your auth server about validity or your auth server could notify your task server(s) to drop sessions for users. You just need some way to make all your servers aware of the revoked access, so yeah multiple places need to be informed somehow. 

The usecase of getting a short-lived, single-use token from your auth server to authenticate against some task server for starting a session is one JWTs could fit in my opinion. 

Share this post


Link to post
Share on other sites

Hi @thomasaull

I have been using this module during the last week, to rebuild my API logic from the ground up. It's really nice work, thank you for releasing it! 😀

One thing I've noticed though, is that the exceptions handler (Router::handleException) is a bit overactive, and shuts everything down on non-critical exceptions. 

For instance, when running a PNG file through the PW ImageResizer ($img->size() etc), PW throws an exception, because the exif_read_data function is not available for PNG's. PW deals with this by using the error control operator (@method): the code still runs fine, while silently throwing an exception message. 

However, using the RestAPI module, this renders (and logs) an error message and stops any further output.   

It is of course easy to just comment out Router.php line 25, where you set the handler. But perhaps this could work in another way? Maybe making it a configurable option?

Share this post


Link to post
Share on other sites

@eelkenet Thanks for using this module and I'm glad it is useful to you 🙂

This is actually the first time, I've heard about the @Operator regarding errors. However, I found an interesting paragraph on the page you have linked to in your post:

Quote

If you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @.

So I added a line, which checks for the error reporting before displaying an error: https://github.com/thomasaull/RestApi/commit/fe63cc48cfcc6d58489f019d5026764cb60d14e5

Could you please manually download the module from the develop branch on Github and give me quick feedback if this resolves your issue? https://github.com/thomasaull/RestApi/archive/develop.zip

  • Thanks 1

Share this post


Link to post
Share on other sites

I ran into an issue that is related to the way the RestAPI circumvents the pagetree structure (running the checkIfApiRequest hook before rendering any page).
This method made it impossible to use ProCache for API requests that could (and should) return a cached result, such as for static site content. I thought about creating a custom caching system on top of RestApi, but ProCache is just too well designed to ignore here.  

I wrote a post about this on the ProCache VIP-forum, but as this forum is not accessible to all people I'd like to share my (admittedly hacky) solution for this. Basically I add another (cacheable) endpoint in the pagetree, which pipes the request to the RestApi endpoint:

  1. Create a new template and corresponding page (I called both 'api').
  2. Set the content-type of this template to application/json, and disable any prepending/appending of files. 
  3. Add the following code to the template:
<?php //site/templates/api.php

$protocol = $config->https ? "https://" : "http://";
$endpoint = $modules->get("RestApi")->endpoint;
$hostname = $config->httpHost;
$segments = implode("/", $input->urlSegments);
$url =  $protocol.$hostname."/".$endpoint.$segments;

return file_get_contents($url);

I'm sure there would be a better, cleaner way of doing this. A current downside is that there now are 2 seemingly identical endpoints for my site.
One is cached, and the other is 'live'. 

Any ideas?

Share this post


Link to post
Share on other sites

Thomas,

I recently found your module, good job. 

Right now im thinkering with Electron and making Processwire to serve as a headless CMS. So your module is quite handy. 

I forked the module on GitHub and made it a little bit more connected to Processwire. To sum things up, I creates a "Endpoint Container" in the page tree where you can add your routes and methods. 

It still needs to add responding classes to provide content ;) I added a skeleton Class called "Blog" to get all contents under the "Home" Page or a specific Page via ID.

I created a Pull Request, maybe you like my approach.

https://github.com/Luis85/RestApi

 

  • Like 2

Share this post


Link to post
Share on other sites

@LuisM Hey Luis, yes I saw it on Github. I'm a little short on time from last week to in a few days, I'm going to get back at you at the PR as soon as possible!

  • Like 1

Share this post


Link to post
Share on other sites

@thomasaull Thanks for this module! It seems to be a great starting point for building an API. 

I have 2 questions:

1. How would you approach a multilanguage API? My idea would be to add a query param to the api call (e.g. /api/posts/?lang=fr ) and switch the user language before getting the field values. Is there another/better solution?

2. I don't need it right now, but how would I implement a session authentification when accessing the api?

 

Thanks!

Share this post


Link to post
Share on other sites

Hey,

Thanks for that  module.

 

in the module description it says:

 

Authorization: JWT

To use JWT-Auth you have to send a GET Request to http://yourhost/api/auth with two parameters, username and password. The API will create and return you the JWT-Token which you have to add as a header to every following request:

 

Actually I think it has to be a POST Request. In the "DefaultRoutes" the Route is defined like this.
 

['POST', '', Auth::class, 'login', ['auth' => false]],

 

Share this post


Link to post
Share on other sites
1 hour ago, pmichaelis said:

Hey,

Thanks for that  module.

 

in the module description it says:

 

Authorization: JWT

To use JWT-Auth you have to send a GET Request to http://yourhost/api/auth with two parameters, username and password. The API will create and return you the JWT-Token which you have to add as a header to every following request:

 

Actually I think it has to be a POST Request. In the "DefaultRoutes" the Route is defined like this.
 


['POST', '', Auth::class, 'login', ['auth' => false]],

 

You're totally right, good catch thank you! I updated the Readme accordingly.

  • Like 1

Share this post


Link to post
Share on other sites
On 12/18/2018 at 4:27 PM, Torsten Baldes said:

@thomasaull Thanks for this module! It seems to be a great starting point for building an API. 

I have 2 questions:

1. How would you approach a multilanguage API? My idea would be to add a query param to the api call (e.g. /api/posts/?lang=fr ) and switch the user language before getting the field values. Is there another/better solution?

2. I don't need it right now, but how would I implement a session authentification when accessing the api?

 

Thanks!

Thanks Thorsten!

How you handle incoming api requests is generally totally up to you – you have all the freedom 🙂 Your idea sounds like a good and easy solution though. However, currently there is no possibility to implement such thing globally on every request. For this maybe it would be a good idea to make the handle() method in Router.php hookable. Maybe you want to test it and provide a PR for this. It would be very welcome 🙂

For Session auth just activate the option in the module settings and make sure to provide the withCredentials option: https://github.com/thomasaull/RestApi/blob/master/README.md#authorization-session. In your frontend app just send a login request to the auth endpoint: https://github.com/thomasaull/RestApi/blob/master/README.md#authorization-jwt and it should (hopefully) work

  • Like 1

Share this post


Link to post
Share on other sites

@LuisM @thomasaull 
Hi, great module(s)!

 

But maybe it could be better 

  1. admin routes / endpoints from PW backend (map endpoint to a pw page / template or any other self defined php file)?
  2. maybe just use PW templates and (sub-)pages from PW page tree (/api/*)?
 
I searched for a simple module to deliver JSON output like Pages2JSON module, but would benefit from auth methods implemented with RestApi module...

Share this post


Link to post
Share on other sites

@pwFoo What exactely do you mean by 1)? Mapping an endpoint to a PW Page is as easy as

$page = wire('pages')->get(1042);

in your endpoint function.

Mapping an endpoint to a php file is the intendend behaviour of the module, check the example: https://github.com/thomasaull/RestApi/blob/master/apiTemplate/Example.php which get's mapped in the Routes.php: https://github.com/thomasaull/RestApi/blob/master/apiTemplate/Routes.php

2) That's basically the approach @LuisM used in his PR. I'm not sure if it's the best solution, check my comment on Github: https://github.com/thomasaull/RestApi/pull/1#issuecomment-450135767

  • Like 1

Share this post


Link to post
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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Anssi
      A simple module to enable easy navigation between the public and the admin side of the site. After installation a green bar will appear to the upper side of the screen, containing a few navigation elements and displaying the PW version number.
      Heavily inspired by @apeisa's great AdminBar (Thanks!). I needed a bit simpler tool for my projects and as a result, this was made. Available on GitHub .

    • By Sebi
      I've created a small module which lets you define a timestamp after which a page should be accessible. In addition you can define a timestamp when the release should end and the page should not be accessable any more.
      Github: https://github.com/Sebiworld/PageAccessReleasetime
      Usage
      PageAccessReleasetime can be installed like every other module in ProcessWire. Check the following guide for detailed information: How-To Install or Uninstall Modules
      After that, you will find checkboxes for activating the releasetime-fields at the settings-tab of each page. You don't need to add the fields to your templates manually.
      Check e.g. the checkbox "Activate Releasetime from?" and fill in a date in the future. The page will not be accessable for your users until the given date is reached.
      If you have $config->pagefileSecure = true, the module will protect files of unreleased pages as well.
      How it works
      This module hooks into Page::viewable to prevent users to access unreleased pages:
      public function hookPageViewable($event) { $page = $event->object; $viewable = $event->return; if($viewable){ // If the page would be viewable, additionally check Releasetime and User-Permission $viewable = $this->canUserSee($page); } $event->return = $viewable; } To prevent access to the files of unreleased pages, we hook into Page::isPublic and ProcessPageView::sendFile.
      public function hookPageIsPublic($e) { $page = $e->object; if($e->return && $this->isReleaseTimeSet($page)) { $e->return = false; } } The site/assets/files/ directory of pages, which isPublic() returns false, will get a '-' as prefix. This indicates ProcessWire (with activated $config->pagefileSecure) to check the file's permissions via PHP before delivering it to the client.
      The check wether a not-public file should be accessable happens in ProcessPageView::sendFile. We throw an 404 Exception if the current user must not see the file.
      public function hookProcessPageViewSendFile($e) { $page = $e->arguments[0]; if(!$this->canUserSee($page)) { throw new Wire404Exception('File not found'); } } Additionally we hook into ProcessPageEdit::buildForm to add the PageAccessReleasetime fields to each page and move them to the settings tab.
      Limitations
      In the current version, releasetime-protected pages will appear in wire('pages')->find() queries. If you want to display a list of pages, where pages could be releasetime-protected, you should double-check with $page->viewable() wether the page can be accessed. $page->viewable() returns false, if the page is not released yet.
      If you have an idea how unreleased pages can be filtered out of ProcessWire selector queries, feel free to write an issue, comment or make a pull request!
    • By David Karich
      Thanks to the great Pro module "RepeaterMatrix" I have the possibility to create complex repeater items. With it I have created a quite powerful page builder. Many different content modules, with many more possible design options. The RepeaterMatrix module supports the cloning of items, but only within the same page. Now I often have the case that very design-intensive pages and items are created. If you want to use this module on a different page (e.g. in the same design), you have to rebuild each item manually every time.
      With this proof of concept I have created a module which adds the feature to copy a repeater item to the clipboard so that you can paste this item to another page with the same repeater field. The module has been developed very rudimentarily so far. It is currently not possible to copy nested items. There is also no check of Min/Max. You can also only copy items that have the same field on different pages. And surely you can solve all this more elegantly with AJAX. But personally I lack the deeper understanding of the repeaters. Also missing on the Javascript side are event triggers for the repeaters, which would make it easier. Like e.g. RepeaterItemInitReady or similar.
      it would be great if @ryan would implement this functionality in the core of RepeaterMatrix. I think he has better ways to implement this. Or what do you think, Ryan?
      Everybody is welcome to work on this module and improve it, if it should not be integrated into the matrix core. Therefore I put it for testing and as download on GitHub: https://github.com/FlipZoomMedia/InputfieldRepeaterMatrixDublicate
      You can best see the functionality in the screencast: 
       
    • By anderson
      Hi,
      Please take a look at this:
      https://templatemag.com/demo/Good/
      The upper nav bar, including dropdowns like "pages" and "portfolios", what do you call this whole thing? At first I guess it's called "dropdown nav bar", but seems not.
      AND of course, what's the simplest way/module to achieve this in PW?
      Thanks in advance.
    • By Sebi2020
      Hey, I'm new and I created a simple module for tagging pages because I didn't found a module for it (sadly this is not a core feature). This module is licensed under the GPL3 and cames with absolutly no warranty at all. You should test the module before using it in production environments. Currently it's an alpha release. if you like the module or have ideas for improvements feel free to post a comment. Currently this fieldtype is only compatible with the Inputfield I've created to because I haven't found  an Inputfield yet, that returns arrays from a single html input.
      Greetings Sebi2020
      FieldtypeTags.zip.asc
      InputfieldTagify.zip
      InputfieldTagify.zip.asc
      FieldtypeTags.zip