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

Thank you @teppo A configurable endpoint ist not really difficult, so I just did it – 0.0.2 has a field in the module settings for that 🙂

  • Like 3

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

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 Robin S
      Another little admin helper module...
      Template Field Widths
      Adds a "Field widths" field to Edit Template that allows you to quickly set the widths of inputfields in the template.

      Why?
      When setting up a new template or trying out different field layouts I find it a bit slow and tedious to have to open each field individually in a modal just to set the width. This module speeds up the process.
      Installation
      Install the Template Field Widths module.
      Config options
      You can set the default presentation of the "Field widths" field to collapsed or open. You can choose Name or Label as the primary identifier shown for the field. The unchosen alternative will become the title attribute shown on hover. You can choose to show the original field width next to the template context field width.  
      https://github.com/Toutouwai/TemplateFieldWidths
      https://modules.processwire.com/modules/template-field-widths/
    • By horst
      Croppable Image 3
      for PW 3.0.20+
      Module Version 1.1.16
      Sponsored by http://dreikon.de/, many thanks Timo & Niko!
      You can get it in the modules directory!
      Please refer to the readme on github for instructions.
       
      -------------------------------------------------------------------------
       
      Updating from prior versions:
       
      Updating from Croppable Image 3 with versions prior to 1.1.7, please do this as a one time step:
      In the PW Admin, go to side -> modules -> new, use "install via ClassName" and use CroppableImage3 for the Module Class Name. This will update your existing CroppableImage3 module sub directory, even if it is called a new install. After that, the module will be recogniced by the PW updater module, what makes it a lot easier on further updates.
      -------------------------------------------------------------------------
       
      For updating from the legacy Thumbnail / CropImage to CroppableImage3 read on here.
       
      -------------------------------------------------------------------------
       
    • By MoritzLost
      UPDATE: I have published a stable version of this module!
      Discussion thread:
      Github: https://github.com/MoritzLost/TextformatterPageTitleLinks
      ---
      Hello there,
      I'm working on a tiny textformatter module that searches the text for titles of other pages on your site and creates hyperlinks to them. I'm not sure if something like this exists already, but I haven't found anything in the module directory, so I wrote my own solution 🙂
      It's not properly tested yet and is still missing some functionality I would like to implement, so at the moment it should be considered in BETA. Features include limiting the pages that will get searched by template, and adding a custom CSS class to the generated hyperlinks. As I'm writing this I noticed that it will probably include unpublished and hidden pages at the moment, so yeah ... it's still in development alright 😅
      You can download the module from Github:
      https://github.com/MoritzLost/TextformatterPageTitleLinks
      There's some more information in the readme as well.
      Anyway, let me know what you think! I'm happy about any feedback, possible improvements or ideas on how to improve the module. Cheers.
    • By blad
      Hi guys!
      I just uploaded a module to explore files based on elFinder. By default it will show the "Files" folder.
      Screenshots:

      Video:
       
      To do:
       More options To fix:
       The function of rotating or scaling an image fails  Image editors V 1.01 (view issue)
      Fixed the bug working with the Multi-Language support ( translation of folders ). Fixed the name of elfinder.en  Github:
      https://github.com/LuisSantiago/ProcessElFinder/
      I hope you like it.
    • By BitPoet
      I'm really in love with FormBuilder, but the one thing missing to match all my end users' expectations were repeatable field groups. Think repeaters, in ProcessWire terms. Our primary application of PW is our corporate intranet, so "lines" of fields are quite common in the forms I build. We have all kinds of request forms where the information for a varying number of colleagues needs to be entered (from meal order to flight booking request) and where it is simply impractical to send a form for each, and I don't want to clutter my forms with multiple instances of fields that may only get used ten percent of the time.
      That's why I started to build FormBuilderMultiplier (link to GitHub).
      What it does:
      Adds an option to make a regular Fieldgroup repeatable Lets you limit the number of instances of a Fieldgroup on the form Adds an "Add row" button the form that adds another instance of the Fieldgroup's fields Adds a counter suffix at the end of every affected field's label Stores the entered values just like regular fields Makes the entered values available in preview and email notifications Supports most text based fields, textareas and selects (really, I haven't had enough time to test all the available choices yet) What it doesn't do (yet):
      Support saving to ProcessWire pages (i.e. real Repeaters) I haven't tested all the validation stuff, Date/Time inputs etc. yet, but since I'm utterly swamped with other stuff at work, I didn't want to wait until I have it polished. Any feedback is welcome. There might also be some issues with different output frameworks that I haven't encountered yet. The forms I work with mostly use UIKit.
      Status:
      Still alpha, so test well before using it in the field.
      Known issues:
      When rows are added, the form's iframe needs to be resized, which isn't completely clean yet.
      How it works:
      The Fieldgroup settings are added through regular hooks, as is the logic that adds the necessary field copies for processing the form and displaying previews.
      "Multiplied" field instances are suffixed with _NUM, where NUM is an incremental integer starting from 1. So if you have add two fields named "surname" and "givenname" to a fieldgroup and check the "multiply" checkbox, the form will initially have "surname_1" and "givenname_1" field (I'm still considering changing that to make the risk to shoot oneself into the foot by having a regular "surname_1" field somewhere else in the form less likely).
      When a "row" is added, the first row is cloned through JS and the counter in the fields' IDs, names and "for" attributes as well as the counter in the label are incremented before appending the copies to the Fieldset container in the form.
      To keep backend and frontend in sync, a hidden field named [name of the fieldset]__multiplier_rows is added to the form. Both the backend and the frontend script use this to store and retrieve the number of "rows".
      ToDo:
      Naturally, add the option to store the data in real repeaters when saving to pages. Do a lot of testing (and likely fixing). Make a few things (like the "Add row" button label etc.) configurable in field(set) context. Add a smooth API to retrieve the multiplied values as WireArrays. The mandatory moving screenshot: