security
Authentication And Authorisation Security
Authentication establishes who a user is. Authorisation decides what that authenticated user may do. A secure application checks both server-side and defaults to denying actions that are not explicitly allowed.
Core Controls
- Use established framework authentication components where possible.
- Regenerate the session ID after login and invalidate sessions on logout.
- Check permissions on every protected action, not only in navigation links.
- Apply least privilege to ordinary users, administrators, API clients, and background jobs.
- Use generic login failures so account existence is not disclosed unnecessarily.
Authorise The Action And Record
A user may be allowed to download invoices but only invoices they own. Check both the broad permission and the specific record.
<?php
declare(strict_types=1);
function canDownloadInvoice(array $user, array $invoice): bool
{
if (($user['role'] ?? '') === 'admin') {
return true;
}
return ($invoice['user_id'] ?? null) === ($user['id'] ?? null);
}
var_dump(canDownloadInvoice(['id' => 10, 'role' => 'customer'], ['user_id' => 10]));
var_dump(canDownloadInvoice(['id' => 11, 'role' => 'customer'], ['user_id' => 10]));
// Prints:
// bool(true)
// bool(false)
Use a central policy layer when the rule appears in several routes or services.
Secure Login Behaviour
Use password_hash() and password_verify() rather than writing password cryptography yourself. Rate-limit login attempts. Regenerate the session ID after successful login. Return a generic failure message so the response does not unnecessarily reveal whether an account exists.
Multi-factor authentication can reduce account-takeover risk for privileged users and sensitive products. Recovery flows need the same care as login because a weak reset path bypasses a strong password.
In Application Work
A hidden button is not an authorisation control. Review the route, controller, service, and record-level policy for each sensitive action. Include API endpoints and background jobs, not only browser pages.
What To Check
Before moving on, make sure you can distinguish authentication from authorisation, protect session transitions, apply record-level checks, and test anonymous, owner, non-owner, and privileged cases.
Practice
Practice: Review An Invoice Download
Requirements
- Require an authenticated user.
- Check ownership or an explicit administrative permission.
- Return the same safe denial shape for unauthorised requests.
- Test anonymous, owner, non-owner, and admin cases.
Show solution
Review Points
- Use established framework authentication components where possible.
- Regenerate the session ID after login and invalidate sessions on logout.
- Check permissions on every protected action, not only in navigation links.
- Apply least privilege to ordinary users, administrators, API clients, and background jobs.
- Use generic login failures so account existence is not disclosed unnecessarily.