| sidebar_position | 4 |
|---|---|
| title | Authentication |
Use the isValidUser() method to validate a username/email and password combination:
<?php
$user = $users->isValidUser('johndoe', 'SecurePass123');
if ($user !== null) {
echo "Authentication successful!";
echo "User ID: " . $user->getUserid();
} else {
echo "Invalid credentials";
}:::tip Login Field
The isValidUser() method uses the login field configured in your UsersService constructor. Pass either LoginField::Email or LoginField::Username when creating the service.
:::
LoginField lives in the ByJG\Authenticate\Enum namespace.
By default, passwords are automatically hashed using SHA-1 when saved. The library uses the PasswordSha1Mapper for this purpose.
<?php
// Password is automatically hashed when saved
$user->setPassword('plaintext password');
$users->save($user);
// The password is stored as SHA-1 hash in the database:::warning SHA-1 Deprecation SHA-1 is used for backward compatibility. For new projects, consider implementing a custom password hasher using bcrypt or Argon2. See Mappers for details. :::
:::tip Enforce Password Strength To enforce password policies (minimum length, complexity rules, etc.), see Password Validation. :::
For modern, stateless authentication, use JWT tokens. This is the recommended approach for new applications as it provides better security and scalability.
<?php
use ByJG\JwtWrapper\JwtHashHmacSecret;
use ByJG\JwtWrapper\JwtWrapper;
// Create JWT wrapper
$jwtSecret = getenv('JWT_SECRET') ?: JwtWrapper::generateSecret(64); // base64 encoded secret
$jwtWrapper = new JwtWrapper('your-server.com', new JwtHashHmacSecret($jwtSecret));
// Create authentication token
$userToken = $users->createAuthToken(
'johndoe', // Login
'SecurePass123', // Password
$jwtWrapper,
3600, // Expires in 1 hour (seconds)
[], // Additional user info to save
['role' => 'admin'] // Additional token data
);
if ($userToken !== null) {
echo "Token: " . $userToken->token;
}Need to include standard user columns (name, email, etc.) automatically? Pass the optional seventh argument with User enum values or strings. See JWT Tokens for details.
:::tip UserToken Return Type
Both createAuthToken() and createInsecureAuthToken() return a UserToken object with three properties:
token- The JWT token stringuser- The UserModel instancedata- Array of token payload data
This provides immediate access to both the token and user information without additional database queries. :::
Use createInsecureAuthToken() when you need to create tokens without password validation:
<?php
// After OAuth authentication or token refresh
$user = $users->getByEmail($email);
$userToken = $users->createInsecureAuthToken(
$user, // Can pass UserModel or login string
$jwtWrapper,
3600
);
echo "Token: " . $userToken->token;See JWT Tokens for complete details and use cases.
<?php
$userToken = $users->isValidToken('johndoe', $jwtWrapper, $token);
if ($userToken !== null) {
$user = $userToken->user;
$tokenData = $userToken->data;
echo "User: " . $user->getName();
echo "Role: " . $tokenData['role'];
}:::info Token Storage
When a JWT token is created, a hash of the token is stored in the user's properties as TOKEN_HASH. This ensures tokens can be invalidated if needed.
:::
:::tip Why JWT? JWT tokens provide stateless authentication, better scalability, and easier integration with modern frontend frameworks and mobile applications. They're also more secure than traditional PHP sessions. :::
The SessionContext class persists the authenticated user ID inside a PSR-6 cache pool. Use this when you need server-managed sessions (for example, classic PHP applications).
<?php
use ByJG\Authenticate\SessionContext;
use ByJG\Cache\Factory;
// 1. Validate user credentials
$user = $users->isValidUser('johndoe', 'SecurePass123');
if ($user !== null) {
// 2. Create session context
$sessionContext = new SessionContext(Factory::createSessionPool());
// 3. Register login
$sessionContext->registerLogin($user->getUserid());
// 4. User is now authenticated
echo "Welcome, " . $user->getName();
}<?php
$sessionContext = new SessionContext(Factory::createSessionPool());
if ($sessionContext->isAuthenticated()) {
$userId = $sessionContext->userInfo();
$user = $users->getById($userId);
echo "Hello, " . $user->getName();
} else {
echo "Please log in";
}<?php
$sessionContext->registerLogout();- Always use HTTPS in production to prevent credential theft
- Implement rate limiting to prevent brute force attacks
- Use strong passwords - see Password Validation
- Set appropriate session timeouts
- Validate and sanitize all user inputs
- Session Context - Manage user sessions
- JWT Tokens - Deep dive into JWT authentication
- Password Validation - Enforce password policies