Jump to content

Module: RestApi


thomasaull

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 17
Link to comment
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?

Link to comment
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 ?

Link to comment
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
Link to comment
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
Link to comment
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)

Link to comment
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. 

Link to comment
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
Link to comment
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
Link to comment
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
Link to comment
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. 

Link to comment
Share on other sites

  • 1 month later...

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?

Link to comment
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
Link to comment
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?

Link to comment
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
Link to comment
Share on other sites

  • 2 weeks later...

@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!

Link to comment
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]],

 

Link to comment
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
Link to comment
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
Link to comment
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...
Link to comment
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
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...