Skip to main content

Authentication

Validating User Credentials

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";
}
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.

Password Hashing

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
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.

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.

UserToken Return Type

Both createAuthToken() and createInsecureAuthToken() return a UserToken object with three properties:

  • token - The JWT token string
  • user - The UserModel instance
  • data - Array of token payload data

This provides immediate access to both the token and user information without additional database queries.

Creating Tokens Without Password Validation

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.

Validating JWT Tokens

<?php
$userToken = $users->isValidToken('johndoe', $jwtWrapper, $token);

if ($userToken !== null) {
$user = $userToken->user;
$tokenData = $userToken->data;

echo "User: " . $user->getName();
echo "Role: " . $tokenData['role'];
}
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.

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.

Session-Based Authentication

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).

Basic Authentication Flow

<?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();
}

Checking Authentication Status

<?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";
}

Logging Out

<?php
$sessionContext->registerLogout();

Security Best Practices

  1. Always use HTTPS in production to prevent credential theft
  2. Implement rate limiting to prevent brute force attacks
  3. Use strong passwords - see Password Validation
  4. Set appropriate session timeouts
  5. Validate and sanitize all user inputs

Next Steps