XF 2.2 API token on API auth

alexAlToader

New member
Hi,

We are trying to build an API on xenforo.
We need a token for each user - which respects the users permissions.
I understand that this token is the one created in admin->Setup->ApiKeys->user->[userName]
I suspect that if we use this token in XF-Api-Key - we can make API calls with user permissions?

If so, on /api/auth, we need to return this token if login is successful.

I cant find this functionality in the docs. The existing /auth/login-token seems to be for frontend not API. (am i right?)

So what I am trying to do is to create the token in login.
The token I think is created in ApiKey->actionSave

The current problem is that when I call

/** @var \XF\Service\ApiKey\Manager $keyManager */
$keyManager = $this->service('XF:ApiKey\Manager', $apiKey);

$this->apiKeySaveProcess($keyManager)->run();

I dont know how to get the key.
When I try to get the key - is null.

$key = $keyManager->getKey();
$key->save();
var_dump( $key->apiKey );

So, if what I am dong is right, then how do I get the key pls?
And which one is t? The apiKey or apiKeyHash?

Best regards,
AlexT
 
I did something similar to this. Here is the code that I used to generate an API key for a user:

PHP:
            $keyScopes = [
                // DEFINE YOUR SCOPES HERE
            ];

            /** @var \XF\Service\ApiKey\Manager $keyManager */
            $keyManager = $this->service('XF:ApiKey\Manager', $apiKey);

            $keyManager->setTitle('[SET A TITLE FOR THIS KEY]');
            $keyManager->setActive(true);
            $keyManager->setScopes(false, $keyScopes);
            $keyManager->setKeyType('user', \XF::visitor()->username);

            // If you need to regenerate a previously created key.
            if ($regenerateCheck = $this->request->filter('regenerate_key', 'uint')) {
                $keyManager->regenerate();
            }

            $keyManager->save();

I think this is what you were asking about.
 
@robdog - and now how do I map this key to the users permissions pls?
The permissions that the user already has - not the ones I set trough the admin api add key.
There are many other permissions...
I just realized those 2 sets might not be connected?
Or do I set allow_all_scopes = true and then the other permissions will apply?

Oh man this took an unexpected turn :)
 
You do not map a key to user permissions. You map a key to API scopes. Your API endpoints will make sure the key has the right scopes before sending back the right information for an API endpoint.

However, you can access the user the key was assigned like this:
Code:
        $key = \XF::apiKey();
        $user = $key->User;

You can then start checking the user permissions if your API endpoint needs to do that.
 
Back
Top Bottom