Jump to content
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 15

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 3

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.

  • Like 1

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By gebeer
      I am happy to present my new fieldtype FieldtypeImageFromPage. It is made up of 2 modules:
      Fieldtype Image Reference From Another Page is a Fieldtype that stores a reference to a single image from another page. The image can be selected with the associated Inputfield.
      Inputfield Select Image From Page is an Inputfield to select a single image from images on a predefined page and it's children.
      And there also is a helper module that takes care of cleanup tasks.
      This module evolved out of a discussion about my other Module FieldtypeImagePicker.  It caters for use cases where a set of images is being reused multiple times across a site. With this fieldtype these images can be administered through a chosen page. All images uploaded to that page will be available in the inputfield.
      When to use ?
      Let editors choose an image from a set of images that is being used site-wide. Ideal for images that are being re-used across the site.
      Suited for images that are used on multiple pages throughout the site (e.g. icons).
      Other than the native ProcessWire images field, the images here are not stored per page. Only references to images on another page are stored. This has several advantages:
      one central place to organize images when images change, you only have to update them in one place. All references will be updated, too. (Provided the name of the image that has changed stays the same) Features
      Images can be manipulated like native ProcessWire images (resizing, cropping etc.) Image names are fully searchable through the API Accidental image deletion is prevented. When you want to delete an image from one of the pages that hold your site-wide images, the module searches all pages that use that image. If any page contains a reference to the image you are trying to delete, deletion will be prevented. You will get an error message to help you edit those pages and remove references there before you can finally delete the image. How to install and setup
      Download and install this module like any other modules in ProcessWire Create a page in the page tree that will hold your images. This page's template must have an images field Upload some images to the page you created in step 2 Create a new field. As type choose 'Image Reference From Another Page'. Save the field. In 'Details' Tab of the field choose the page you created in step 2 Click Save button Choose the images field name for the field that holds your images (on page template from step 2) Click Save button again Choose whether you want to include child pages of page from step 2 to supply images Add the field to any template You are now ready to use the field View of the inputfield on the page edit screen:

      View of the field settings

      The module can be installed from this github repo. Some more info in the README there, too.
      In my tests it was fairly stable. After receiving your valued feedback, I will eventually add it to the modules directory.
      My ideas for further improvement:
      - add ajax loading of thumbnails
      Happy to hear your feedback!
       
    • By gebeer
      Although the PW backend is really intuitive, ever so often my clients need some assistance. Be it they are not so tech savvy or they are not working in the backend often.
      For those cases it is nice to make some help videos available to editors. This is what this module does.
      ProcessHelpVideos Module
      A Process module to display help videos for the ProcessWire CMS. It can be used to make help videos (screencasts) available to content editors.
      This module adds a 'Help Videos" section to the ProcessWire backend. The help videos are accessible through an automatically created page in the Admin page tree. You can add your help videos as pages in the page tree. The module adds a hidden page to the page tree that acts as parent page for the help video pages. All necessary fields and templates will be installed automatically. If there are already a CKEditor field and/or a file field for mp4 files installed in the system, the module will use those. Otherwise it will create the necessary fields. Also the necessary templates for the parent help videos page and it's children are created on module install. The module installs a permission process-helpvideos. Every user role that should have access to the help video section, needs this permission. I use the help video approach on quite a few production sites. It is stable so far and well received by site owners/editors. Up until now I installed required fields, templates and pages manually and then added the module. Now I added all this logic to the install method of the module and it should be ready to share.
      The module and further description on how to use it is available on github: https://github.com/gebeer/ProcessHelpVideos
      If you like to give it a try, I am happy to receive your comments/suggestions here.
    • By Robin S
      A module created in response to the topic here:
      Page List Select Multiple Quickly
      Modifies PageListSelectMultiple to allow you to select multiple pages without the tree closing every time you select a page.
      The screencast says it all:

       
      https://github.com/Toutouwai/PageListSelectMultipleQuickly
      https://modules.processwire.com/modules/page-list-select-multiple-quickly/
    • By gebeer
      Hello all,
      sharing my new module FieldtypeImagePicker. It provides a configurable input field for choosing any type of image from a predefined folder.
      The need for it came up because a client had a custom SVG icon set and I wanted the editors to be able to choose an icon in the page editor.
      It can also be used to offer a choice of images that are used site-wide without having to upload them to individual pages.
      There are no image manipulation methods like with the native PW image field.
      Module and full description can be found on github https://github.com/gebeer/FieldtypeImagePicker
      Kudos to @Martijn Geerts. I used his module FieldTypeSelectFile as a base to build upon.
      Here's how the input field looks like in the page editor:

      Hope it can be of use to someone.
      If you like to give it a try, I'm happy to hear your comments or suggestions for improvement. Eventually this will go in the module directory soon, too.
    • By bernhard
      @Sergio asked about the pdf creation process in the showcase thread about my 360° feedback/survey tool and so I went ahead and set my little pdf helper module to public.
      Description from PW Weekly:
       
      Modules Directory: https://modules.processwire.com/modules/rock-pdf/
      Download & Docs: https://github.com/BernhardBaumrock/RockPDF
       
      You can combine it easily with RockReplacer: 
      See also a little showcase of the RockPdf module in this thread:
       
×
×
  • Create New...