0% complete

Authentication · Lesson 7 of 7

Role-Based Access

Authorize actions using explicit roles or, preferably, granular permissions.

Lesson

Role-based access maps users to roles and roles to permitted actions. Check permission at the server-side operation, not only in the interface. For multi-tenant data, also verify the resource belongs to the user's organization. Keep role definitions centralized and test denial as well as success. Never accept the role or permission from a form field or query parameter. Further guidance Use PHP password hashing APIs, regenerate a session identifier after authentication, and clear session state during logout. Authentication identifies the user; authorization checks whether that user may perform this action on this record. Rate-limit sensitive endpoints and keep failure messages generic. Practice task: Create a fresh example for Role-Based Access. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

Role-Based Access
PHP
$canManage = in_array($user['role'] ?? '', ['admin', 'editor'], true);
if (! $canManage) {
    http_response_code(403);
    exit('Forbidden');
}
Expected output
HTTP 403 when the current user lacks the allowed role

Key points

  • Authorize actions using explicit roles or, preferably, granular permissions.
  • Store password hashes, not plaintext passwords.
  • Check authorization on every protected operation.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.