I'm starting to work with Codeigniter 4 Shield.
I added this piece of code to my app/Config/Routes.php file.
$routes->get('/access/token', static function() {
$token = auth()->user()->generateAccessToken(service('request')->getVar('token_name'));
return json_encode(['token' => $token->raw_token]);
});
When I try to access the route in my web browser using the URL https://example.com/access/token, I obtain the error:
Call to a member function generateAccessToken() on null
produced by the line of code below:
$token = auth()->user()->generateAccessToken(service('request')->getVar('token_name'));
Background information:
- I have installed Codeigniter 4 Shield using Composer, ran the respective database migrations, and everything else works fine.
- My Codeigniter 4 Shield 'login' and 'register' pages work fine.
How can I load generateAccessToken() automatically in the app/Config/Routes.php file?
You need to submit the login credentials (email & password) along with your HTTP
POSTrequest to help identify the User requesting the access token. Otherwise,auth()->user()is empty, hence the error.To generate an access token, you need to first authenticate the User.
For example: (Using
email&password)->post(...)instead of->get(...).File: app/Config/Routes.php
File: app/Controllers/Auth/LoginController.php
/apiroutes using the$filterssetting onapp/Config/Filters.php. Read: Protecting Routes"auth/token") route together with all API routes ("api/*") from the global"session"&"toolbar"filters.File: app/Config/Filters.php
POSTrequest to theauth/tokenroute to receive the 'access token'. Upon receiving the token, store it with the client. I.e: in localStorageAuthorizationheader along with all your other protected API HTTP requests in your application without reauthenticating the user. i.e: