Download the PHP package activecollab/authentication without Composer
On this page you can find all versions of the php package activecollab/authentication. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download activecollab/authentication
More information about activecollab/authentication
Files in activecollab/authentication
Package authentication
Short Description Authenticate user
License MIT
Homepage https://labs.activecollab.com
Informations about the package authentication
Authentication Library
Table of Contents:
- Who are Authenticated Users
- Accessing Users
- Authorizers
- Request Aware Authorizers
- Exception Aware Authorizers
- Transports
- Events
- Authentication Middlewares
- Working with Passwords
- Hashing and Validating Passwords
- Password Policy
- Generating Random Passwords
- Login Policy
- To Do
Who are Authenticated Users?
Authentication library builds on top of activecollab/user
package. There are three types of visitors that we recognize:
- Unidentified visitors - Visitors that we know nothing bout,
- Identified visitors - People that we identified when they provided their email address,
- Users with accounts - People with actual accounts in our application.
Only users with accounts in our application can be authenticated.
Accessing Users
Write a class that implements ActiveCollab\Authentication\AuthenticatedUser\RepositoryInterface
when integrating this package. Implementation of this interface will let the library find users by their ID and username:
Authorizers
Authorizers are used to authorize user credentials against data that is stored by a particular authentication service (stored users, LDAP/AD, IdP etc).
Key authorizer method is verifyCredentials
. It receives an array with credentials and it is expected to return ActiveCollab\Authentication\AuthenticatedUser\AuthenticatedUserInterface
instance on successful authorization, or null
when authorization is not successful. Some implementations may decide to throw exceptions, to make a clear distinction between various reasons why authorization failed (user not found, invalid password, user account is temporarily or permanently suspended etc).
Example of Authorizer implementation that fetches user from users repository, and validates user's password:
Request Aware Authorizers
Request aware authorizers go a step further. They offer a mechanism to receive PSR-7 request, and extract credentials and default payload from them (or based on them). This is useful when authorizer requires request data validation and parsing. For example, SAML authorizer will need to parse SAML payload in order to extract relevant credentials from it.
For authorizer to become request aware, it additionally needs to implement ActiveCollab\Authentication\Authorizer\RequestAware\RequestAwareInterface
, and implement request processor that can take in Psr\Http\Message\ServerRequestInterface
and return processing result:
Exception Aware Authorizers
Authorizers can be set to be exception aware. Such authorizers have handleException()
method that should be called on authorization exception. For system to consider an authorizer to be exception aware, it needs to implement ActiveCollab\Authentication\Authorizer\ExceptionAware\ExceptionAwareInterface
interface.
This is useful if you need to handle error in a particular way (redirect user to an external SSO for example), or if you want to implement some extra measures of protections (like brute force login protection, as demonstrated below):
Additionally, exception handling can be delegated to exception handlers. For default ExceptionAware
to detect that authorizer uses handler to handle an exception, authorizer needs to implement ActiveCollab\Authentication\Authorizer\ExceptionAware\DelegatesToHandler\DelegatesToHandlerInterface
.
All built in authorizers are exception aware, and can receive a handler:
Transports
During authentication and authorization steps, this library returns transport objects that encapsulate all auth elements that are relevant for the given step in the process:
AuthenticationTransportInterface
is returned on initial authentication. It can be empty, when request does not bear any user ID embedded (token, or session), or it can contain information about authenticated user, way of authentication, used adapter etc, when system finds valid ID in the request.AuthroizationTransportInterface
is returned when user provides their credentials to the authorizer.CleanUpTransportInterface
is returned when there's ID found in the request, but it expired, and needs to be cleaned up.DeauthenticationTransportInterface
- is returned when user requests to be logged out of the system.
Authentication and authorization transports can be applied to responses (and requests) to sign them with proper identification data (set or extend user session cookie for example):
Events
Authentication utility throws events for which you can write handlers. Here's an example:
As you can see from the example above, you can provide multiple handlers for the same event. Following events are available:
onUserAuthenticated
- (visit) User is recognized by its session cookie, token etc, so it was authenticated. Arguments provided to the callback are user instance [AuthenticatedUserInterface], and authentication result [AuthenticationResultInterface].onUserAuthorized
(login) User provided valid credentials, and system authorized it. Arguments provided to the callaback are user instance [AuthenticatedUserInterface], and authentication result [AuthenticationResultInterface].onUserAuthorizationFailed
(login failed) User tried to authorize, but provided credentials were not valid, or authorization failed due to other reasons (SSO service down, etc). Arguments provided to the callback are user's credentials [array], as well as the failure reason ([Exception] or [Throwable]).onUserSet
- User is set - authenticated, authorizer, or app set the user using its own logic. Argument provided to the callback is the user instance [AuthenticatedUserInterface].setOnUserDeauthenticated
(logout) User logged out. Argument provided to the callback is authentication method that got terminated [AuthenticationResultInterface].
Authentication Middlewares
AuthenticationInterface
interface assumes that implementation will be such that it can be invoked as a middleware in a PSR-7 middleware stack. That is why implementation of __invoke
method in middleware stack fashion is part of the interface.
Default implementation of the interface (ActiveCollab\Authentication\Authentication
) is implemented in such way that it initializes authentication by looking at server request when it is invoked. Initialization process will look for an ID in the request (token, session cookie, etc, depending on the used adapters), and loading proper user account when found. User and method of authentication (token, session, etc) are set as request attributes (authenticated_user
, and authenticated_with
respectively) and passed down the middleware stack. You can check these attributes in inner middlewares:
Here's an example of middleware that checks for authenticated user, and returns 401 Unauthorized status if user is not authenticated:
During request handling, authentication can change:
- User can log in,
- User can log out,
- System may request that authentication artifacts (like cookies) are cleaned up.
System can communicate these changes by making appropriate authentication transports that encapsulate information about these events available in a value container, and handing them over to ActiveCollab\Authentication\Middleware\ApplyAuthenticationMiddleware
:
Note: Value container may be any object that implements ActiveCollab\ValueContainer\ValueContainerInterface
. This container can wrap around DI container, or any other mean of value storage. For the convenience we provide a value container that wraps around server request (RequestValueContainer
), that can extract transport from request attributes:
Example above will tell ApplyAuthenticationMiddleware
to check for authentication_transport
attribute, and apply it to request and response if found.
Second argument of ApplyAuthenticationMiddleware
's constructor is $apply_on_exit
argument. It lets you configure when transport will be applied - when entering middleware stack, or when existing it. Default is false
(when entering middleware stack):
Note: Reason why we do this in a separate middleware, instead of exiting part of Authentication middleware is because we may need to clean up request (remove invalid cookie for example).
Working with Passwords
Hashing and Validating Passwords
Passwords can be hashed using one of the three mechanisms:
- PHP's built in
password_*
functions. This is default and recommended method - Using PBKDF2
- Using SHA1
Later two are there for compatibility reasons only, so you can transition your hashed passwords to PHP's password management system if you have not done that already. Password manager's needsRehash()
method will always recommend rehashing for PBKDF2 and SHA1 hashed passwords.
Example:
Library offers a way to check if password needs to be rehashed, usually after you successfully checked if password that user provided is correct one:
Password Policy
All passwords are validated against password policies. By default, policy will accept any non-empty string:
Policy can enforce following rules:
- Password is longer than N characters
- Password contains at least one number
- Password contains mixed case (uppercase and lowercase) letters
- Password contains at least one of the following symbols:
,.;:!$\%^&~@#*
Here's an example where all rules are enforced:
Password policy implements \JsonSerializable
interface, and can be safely encoded to JSON using json_encode()
.
Generating Random Passwords
Password strength validator can also be used to prepare new passwords that meet the requirements of provided policies:
Password generator uses letters and numbers by default, unless symbols are required by the provided password policy.
Note that generator may throw an exception if it fails to prepare a password in 10000 tries.
Login Policy
Login Policy is used by adapters to publish their log in page settings. These settings include:
- Format of username fields. Supported values are
email
andusername
, - Whether "Remember Me" option for extended sessions is supported by the adapter,
- Whether passwords can be changed by the user,
- Log in, log out, password reset and update profile URL-s. These URL-s are used by adapters which implement off-site authentication, so application that uses these adapters can redirect users to correct pages.
This example shows how different settings can be configured using setter calls. All these settings can also be set when you construct new LoginPolicy
instance:
Login policy implements \JsonSerializable
interface, and can be safely encoded to JSON using json_encode()
.
To Do
- Consider adding previously used passwords repository, so library can enforce no-repeat policy for passwords.
- Remove deprecated
AuthenticationInterface::setOnAuthenciatedUserChanged()
.
All versions of authentication with dependencies
ext-json Version *
ext-mbstring Version *
activecollab/cookies Version ^3.0
activecollab/user Version ^4.0
google/apiclient Version ^2.1
psr/http-server-middleware Version ^1.0