fyre / auth
An authentication and authorization library.
Requires
- fyre/config: ^4.1
- fyre/container: ^1.0
- fyre/error: ^6.0
- fyre/inflector: ^3.0
- fyre/middleware: ^6.0
- fyre/orm: ^10.0
- fyre/router: ^7.0
- fyre/server: ^4.1
- fyre/session: ^5.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.59
- fyre/php-cs-fixer-config: ^1.0
- phpunit/phpunit: ^11
README
FyreAuth is a free, open-source authentication/authorization library for PHP.
Table Of Contents
- Installation
- Basic Usage
- Methods
- Access
- Identifier
- Authenticators
- Policy Registry
- Policies
- Middleware
Installation
Using Composer
composer require fyre/auth
In PHP:
use Fyre\Auth\Auth;
Basic Usage
$auth = new Auth($container, $router, $config)
Default configuration options will be resolved from the "Auth" key in the Config.
$options
is an array containing the configuration options.loginRoute
is a string representing the login route alias, and will default to "login".authenticators
is an array containing configuration options for the authenticators.identifier
is an array containing configuration options for the Identifier.identifierFields
is string orn array containing the identifier field name(s), and will default to "email".passwordField
is a string representing the password field name, and will default to "password".modelAlias
is a string representing the model alias, and will default to "Users".queryCallback
is a Closure that will execute before running an identify query, and will default to null.
$container->use(Config::class)->set('Auth', $options);
Autoloading
It is recommended to bind the Auth to the Container as a singleton.
$container->singleton(Auth::class);
Any dependencies will be injected automatically when loading from the Container.
$auth = $container->use(Auth::class);
Methods
Access
Get the Access.
$access = $auth->access();
Add Authenticator
Add an Authenticator.
$authenticator
is an Authenticator.$key
is a string representing the authenticator key, and will default to the Authenticator class name.
$auth->addAuthenticator($authenticator, $key);
Attempt
Attempt to login as a user.
$identifier
is a string representing the user identifier.$password
is a string representing the user password.$rememberMe
is a boolean indicating whether the user should be remembered, and will default to false.
$user = $auth->attempt($identifier, $password, $rememberMe);
Authenticator
Get an authenticator by key.
$key
is a string representing the authenticator key.
$authenticator = $auth->authenticator($key);
Authenticators
Get the authenticators.
$authenticators = $auth->authenticators();
Get Login URL
Get the login URL.
$redirect
is a string or Uri representing the redirect URL, and will default to null.
$url = $auth->getLoginUrl($redirect);
Identifier
Get the Identifier.
$identifier = $auth->identifier();
Is Logged In
Determine if the current user is logged in.
$isLoggedIn = $auth->isLoggedIn();
Login
Login as a user.
$user
is an Entity representing the user.$rememberMe
is a boolean indicating whether the user should be remembered, and will default to false.
$auth->login($user, $rememberMe);
Logout
Logout the current user.
$auth->logout();
User
Get the current user.
$user = $auth->user();
Access
After
Execute a callback after checking rules.
$afterCallback
is a Closure that accepts the current user, access rule name, current result and any additional arguments.
$access->after($afterCallback);
Allows
Check whether an access rule is allowed.
$rule
is a string representing the access rule name or Policy method.
Any additional arguments supplied will be passed to the access rule callback or Policy method.
$result = $access->allows($rule, ...$args);
Any
Check whether any access rule is allowed.
$rules
is an array containing access rule names or Policy methods.
Any additional arguments supplied will be passed to the access rule callbacks or Policy methods.
$result = $access->any($rules, ...$args);
Authorize
Authorize an access rule.
$rule
is a string representing the access rule name or Policy method.
Any additional arguments supplied will be passed to the access rule callback or Policy method.
$access->authorize($rule, ...$args);
Before
Execute a callback before checking rules.
$beforeCallback
is a Closure that accepts the current user, access rule name and any additional arguments.
$access->before($beforeCallback);
Clear
Clear all rules and callbacks.
$access->clear();
Define
Define an access rule.
$rule
is a string representing the access rule name.$callback
is a Closure that accepts the current user and any additional arguments.
$access->define($rule, $callback);
Denies
Check whether an access rule is not allowed.
$rule
is a string representing the access rule name or Policy method.
Any additional arguments supplied will be passed to the access rule callback or Policy method.
$result = $access->denies($rule, ...$args);
None
Check whether no access rule is allowed.
$rules
is an array containing access rule names or Policy methods.
Any additional arguments supplied will be passed to the access rule callbacks or Policy methods.
$result = $access->none($rules, ...$args);
Identifier
Attempt
Attempt to identify a user.
$identifier
is a string representing the user identifier.$password
is a string representing the user password.
$user = $identifier->attempt($identifier, $password);
Get Identifier Fields
Get the user identifier fields.
$identifierFields = $identifier->getIdentifierFields();
Get Model
Get the identity Model.
$model = $identifier->getModel();
Get Password Field
Get the user password field.
$passwordField = $identifier->getPasswordField();
Identify
Find an identity by identifier.
$identifier
is a string representing the user identifier.
$user = $identifier->identify($identifier);
Authenticators
Custom authenticators can be created by extending the \Fyre\Auth\Authenticator
class, and overwriting the below methods as required.
Authenticate
Authenticate a ServerRequest.
$request
is a ServerRequest.
$user = $authenticator->authenticate($request);
Before Response
Update the ClientResponse before sending to client.
$response
is a ClientResponse.
$response = $authenticator->beforeResponse($response);
Login
Login as a user.
$user
is an Entity representing the user.$rememberMe
is a boolean indicating whether the user should be remembered, and will default to false.
$authenticator->login($user, $rememberMe);
Logout
Logout the current user.
$authenticator->logout();
Cookie
use Fyre\Auth\Authenticators\CookieAuthenticator;
The cookie authenticator can be loaded using custom configuration.
$auth
is an Auth.$options
is an array containing configuration options.cookieName
is a string representing the cookie name, and will default to "auth".cookieOptions
is an array containing additional options for setting the cookie.expires
is a number representing the cookie lifetime, and will default to null.domain
is a string representing the cookie domain, and will default to "".path
is a string representing the cookie path, and will default to "/".secure
is a boolean indicating whether to set a secure cookie, and will default to false.httpOnly
is a boolean indicating whether to the cookie should be HTTP only, and will default to true.sameSite
is a string representing the cookie same site, and will default to "Lax".
identifierField
is a string representing the identifier field of the user, and will default to "email".passwordfield
is a string representing the password field of the user, and will default to "password".salt
is a string representing the salt to use when generating the token, and will default to null.
$authenticator = new CookieAuthenticator($auth, $options);
This authenticator is only active when the $rememberMe
argument is set to true in the $auth->attempt
or $auth->login
methods.
Session
use Fyre\Auth\Authenticators\SessionAuthenticator;
The session authenticator can be loaded using custom configuration.
$auth
is an Auth.$session
is a Session.$options
is an array containing configuration options.sessionKey
is a string representing the session key, and will default to "auth".sessionField
is a string representing the session field of the user, and will default to "id".
$authenticator = new SessionAuthenticator($auth, $session, $options);
Token
use Fyre\Auth\Authenticators\TokenAuthenticator;
The token authenticator can be loaded using custom configuration.
$auth
is an Auth.$options
is an array containing configuration options.tokenHeader
is a string representing the token header name, and will default to "Authorization".tokenHeaderPrefix
is a string representing the token header prefix, and will default to "Bearer".tokenQuery
is a string representing the query parameter, and will default to null.tokenField
is a string representing the token field of the user, and will default to "token".
$authenticator = new TokenAuthenticator($auth, $options);
Policy Registry
use Fyre\Auth\PolicyRegistry;
$policyRegistry = new PolicyRegistry($container, $inflector);
Add Namespace
Add a namespace for loading policies.
$namespace
is a string representing the namespace.
$policyRegistry->addNamespace($namespace);
Build
Build a Policy.
$alias
is a string representing the Model alias or class name.
$policy = $policyRegistry->build($alias);
Clear
Clear all namespaces and policies.
$policyRegistry->clear();
Get Namespaces
Get the namespaces.
$namespaces = $policyRegistry->namespaces();
Has Namespace
Determine if a namespace exists.
$namespace
is a string representing the namespace.
$hasNamespace = $policyRegistry->hasNamespace($namespace);
Map
Map an alias to a Policy class name.
$alias
is a string representing the Model alias or class name.$className
is a string representing the Policy class name.
$policyRegistry->map($alias, $className);
Remove Namespace
Remove a namespace.
$namespace
is a string representing the namespace.
$policyRegistry->removeNamespace($namespace);
Resolve Alias
Resolve a modal alias.
$alias
is a model alias or class name.
$alias = $policyRegistry->resolveAlias($alias);
Unload
Unload a policy.
$alias
is a string representing the Model alias or class name.
$policyRegistry->unload($alias);
Use
Load a shared Policy instance.
$alias
is a string representing the Model alias or class name.
$policy = $policyRegistry->use($alias);
Policies
Policies can be created by suffixing the singular model alias with "Policy" as the class name.
Policy rules should be represented as methods on the class, that accept the current user and resolved Entity as arguments.
Middleware
Auth Middleware
use Fyre\Auth\Middleware\AuthMiddleware;
This middleware will authenticate using the loaded authenticators, and add any authentication headers to the response.
$auth
is an Auth.
$middleware = new AuthMiddleware($auth);
Any dependencies will be injected automatically when loading from the Container.
$middleware = $container->use(AuthMiddleware::class);
Handle
Handle a ServerRequest.
$request
is a ServerRequest.$next
is a Closure.
$response = $middleware->handle($request, $next);
This method will return a ClientResponse.
Authenticated Middleware
use Fyre\Auth\Middleware\AuthenticatedMiddleware;
This middleware will throw an UnauthorizedException or return a login RedirectResponse if the user is not authenticated.
$auth
is an Auth.
$middleware = new AuthenticatedMiddleware($auth);
Any dependencies will be injected automatically when loading from the Container.
$middleware = $container->use(AuthenticatedMiddleware::class);
Handle
Handle a ServerRequest.
$request
is a ServerRequest.$next
is a Closure.
$response = $middleware->handle($request, $next);
This method will return a ClientResponse.
Authorized Middleware
use Fyre\Auth\Middleware\AuthorizedMiddleware;
This middleware will throw a ForbiddenException or a login RedirectResponse if the user is not authorized.
$auth
is an Auth.
$middleware = new AuthorizedMiddleware($auth);
Any dependencies will be injected automatically when loading from the Container.
$middleware = $container->use(AuthorizedMiddleware::class);
Handle
Handle a ServerRequest.
$request
is a ServerRequest.$next
is a Closure.
$response = $middleware->handle($request, $next);
This method will return a ClientResponse.
Unauthenticated Middleware
use Fyre\Auth\Middleware\UnauthenticatedMiddleware;
This middleware will throw a NotFoundException if the user is authenticated.
$auth
is an Auth.
$middleware = new UnauthenticatedMiddleware($auth);
Any dependencies will be injected automatically when loading from the Container.
$middleware = $container->use(UnauthenticatedMiddleware::class);
Handle
Handle a ServerRequest.
$request
is a ServerRequest.$next
is a Closure.
$response = $middleware->handle($request, $next);
This method will return a ClientResponse.