Auth
True\Auth covers three common authentication patterns: bearer tokens for API requests, login-token sessions for browser users, and HTTP Basic Authentication.
Setup
Instantiate the class on $App->auth in init.php. Override the bearer-token file path if you don't want the default location:
// default path — BP/app/data/auth-tokens
$App->auth = new True\Auth;
// custom path
$App->auth = new True\Auth([
'bearerTokensFile' => BP.'/app/other-path/auth-tokens',
]);
Bearer tokens
Generate a new token and write it to the tokens file:
echo $App->auth->requestToken();
Open the tokens file, copy the bottom line, and send it with each API request:
Authorization: Bearer sdfsdfsSAMPLE_TOKENjlk5324klj5
Validate the request inside a controller or route callback:
if ($App->auth->authenticate(['type' => 'bearer'])) {
echo json_encode(['result' => 'success']);
} else {
echo json_encode(['result' => 'bearer token invalid']);
}
Login-token sessions
For browser-based logins, store the issued login token in a cookie and pass it back to authenticate(). The call returns the numeric user id on success or false on failure:
$userId = $App->auth->authenticate([
'type' => 'login-token',
'token' => $_COOKIE['login_cookie'],
]);
if (is_numeric($userId)) {
echo json_encode(['result' => 'success', 'page' => $output]);
} else {
echo json_encode(['result' => 'not logged in']);
}
HTTP Basic Authentication
Clients send credentials in the standard Authorization: Basic <base64(username:password)> header. The server decodes it and runs your validation logic.
$App->auth->authenticate(['type' => 'basic']);
Add your credential check in the validateBasicCredentials method on the Auth class. A successful authentication returns an OK response; a failed one returns an HTTP 401.
Example exchange
GET /api/resource HTTP/1.1
Authorization: Basic am9obmRvZTpwYXNzd29yZDEyMw==
Success body:
{ "status": "success", "message": "Authenticated" }
Failure body:
{ "status": "error", "message": "Unauthorized" }