The following warnings occurred:
Warning [2] Undefined variable $unreadreports - Line: 26 - File: global.php(961) : eval()'d code PHP 8.2.25 (Linux)
File Line Function
/global.php(961) : eval()'d code 26 errorHandler->error
/global.php 961 eval
/printthread.php 16 require_once



UserSpice
Using UserSpice accounts with REST API? - Printable Version

+- UserSpice (https://userspice.com/forums)
+-- Forum: Miscellaneous (https://userspice.com/forums/forumdisplay.php?fid=28)
+--- Forum: Documentation (https://userspice.com/forums/forumdisplay.php?fid=30)
+--- Thread: Using UserSpice accounts with REST API? (/showthread.php?tid=1069)



Using UserSpice accounts with REST API? - codsane - 05-29-2018

Hey there!

I recently discovered UserSpice, and I've been loving it as a user management framework for my latest project.

I've realized my project would benefit from a REST API, and I've given my partner the task to manage it. I prefer to use Python because it's something my partner is comfortable with, that way I can handle the PHP stuff and allow them to work on setting up endpoints for the API.

I now have a Python REST API demo working, however the last thing I have to work out before handing it over to my partner is authentication. Is there any way that I can check against the browsers session to see whether or not a user is logged in?

For example, I have the endpoint: api.mydomain.com/players

I will be using AJAX to call that endpoint from one of my pages, but I'd like to protect that endpoint from unauthorized requests outside of my page. This also allows me to log anybody who attempts to abuse the API outside of normal usage.

How can I utilize UserSpice alongside cookies/sessions/hashes in a way that will allow me to accomplish that?


Using UserSpice accounts with REST API? - codsane - 05-30-2018

I thought I'd go ahead and add my own reply to explain how I solved this problem just in case anyone searching is having the same thoughts. After a nights rest I realized the implementation is much simpler than I had originally thought.

First, I went ahead and modified usersc/scripts/during_user_creation.php to generate an API key for each user upon registration. You can read more about cryptography and the generation of secure API keys here. I went with a simple approach:
Code:
$key = bin2hex(openssl_random_pseudo_bytes(16));

Then, I went ahead and included a hidden input within the pages that I will be using my API on.
Code:
<input type="hidden" name="key" value="<?=$user->data()->api_key;?>" />

Now, via JS and AJAX I will be able to grab that API key from the hidden input and make calls to my API. Upon every request to my API, the key is checked against the database to ensure that the key exists. Assuming your key generation method is secure, there will be no way for anyone to make anonymous requests to the API - all calls to the API will be able to be traced to a username in the event of abuse.