Skip to main content
Version: CANARY 🚧

Authentication

Introduction​

BowPHP provides a flexible authentication system supporting two methods: session-based authentication and JWT (JSON Web Token) authentication.

Configuration​

The config/auth.php file defines the guards and their settings:

config/auth.php
return [
// Default guard
'default' => 'web',

// Session authentication
'web' => [
'type' => 'session',
'model' => App\Models\User::class,
'credentials' => [
'username' => 'email',
'password' => 'password',
],
],

// JWT authentication (API)
'api' => [
'type' => 'jwt',
'model' => App\Models\User::class,
'credentials' => [
'username' => 'email',
'password' => 'password',
],
],
];

User model​

The user model must extend Bow\Auth\Authentication:

app/Models/User.php
namespace App\Models;

use Bow\Auth\Authentication;

class User extends Authentication
{
protected ?string $table = 'users';

// For JWT: custom attributes in the token
public function customJwtAttributes(): array
{
return [
'role' => $this->role,
];
}
}

Session authentication​

Login​

use Bow\Auth\Auth;

// Login attempt
$credentials = [
'email' => $request->get('email'),
'password' => $request->get('password'),
];

if (Auth::guard('web')->attempts($credentials)) {
return redirect('/dashboard');
}

return back()->withErrors(['message' => 'Identifiants incorrects']);

Using the helper​

// app_auth helper
if (app_auth('web')->attempts($credentials)) {
return redirect('/dashboard');
}

Checking authentication​

// Is the user logged in?
if (Auth::guard('web')->check()) {
// Logged in
}

// Is the user not logged in?
if (Auth::guard('web')->guest()) {
// Not logged in
}

Retrieving the user​

// Full instance
$user = Auth::guard('web')->user();
echo $user->name;

// ID only
$userId = Auth::guard('web')->id();

Manual login​

$user = User::where('email', $email)->first();

if ($user && Hash::check($password, $user->password)) {
Auth::guard('web')->login($user);
}

Logout​

Auth::guard('web')->logout();

return redirect('/login');

JWT authentication​

Installation required

To use JWT, install the Policier package:

composer require bowphp/policier

JWT configuration​

config/policier.php
return [
'signkey' => app_env('APP_JWT_SECRET'),
'exp' => 3600 * 24 * 7, // 7 days
'iss' => app_env('APP_URL', 'http://localhost'),
'aud' => app_env('APP_URL', 'http://localhost'),
'alg' => 'HS512',
];

API login​

use Bow\Auth\Auth;

class AuthController
{
public function login(Request $request)
{
$credentials = $request->only(['email', 'password']);

if (!Auth::guard('api')->attempts($credentials)) {
return response()->json([
'error' => 'Identifiants incorrects'
], 401);
}

$token = Auth::guard('api')->getToken();

return response()->json([
'token' => $token->getValue(),
'expires_in' => $token->get('exp'),
]);
}

public function me(Request $request)
{
$user = Auth::guard('api')->user();

return response()->json($user);
}

public function logout()
{
Auth::guard('api')->logout();

return response()->json(['message' => 'DΓ©connectΓ©']);
}
}

Client-side usage​

# With the Authorization header
curl -H "Authorization: Bearer TOKEN" https://api.example.com/me

Middlewares​

Authentication middleware​

routes/app.php
// Routes protected by session
$app->get('/dashboard', 'DashboardController::index')->middleware('auth');

// Routes protected by JWT
$app->get('/api/profile', 'Api\ProfileController::show')->middleware('api');

Grouping protected routes​

routes/app.php
$app->prefix('/admin')->middleware('auth')->group(function () use ($app) {
$app->get('/users', 'Admin\UserController::index');
$app->get('/settings', 'Admin\SettingsController::index');
});

$app->prefix('/api/v1')->middleware('api')->group(function () use ($app) {
$app->get('/me', 'Api\UserController::me');
$app->put('/me', 'Api\UserController::update');
});

Custom middleware​

app/Middlewares/CustomAuthMiddleware.php
namespace App\Middlewares;

use Bow\Auth\Auth;
use Bow\Http\Request;

class CustomAuthMiddleware
{
public function process(Request $request, callable $next)
{
if (Auth::guard('web')->guest()) {
return redirect('/login');
}

return $next($request);
}
}

Complete example​

Authentication controller​

app/Controllers/AuthController.php
namespace App\Controllers;

use App\Models\User;
use Bow\Auth\Auth;
use Bow\Http\Request;
use Bow\Security\Hash;

class AuthController
{
public function showLogin()
{
if (Auth::guard('web')->check()) {
return redirect('/dashboard');
}

return view('auth/login');
}

public function login(Request $request)
{
$validation = $request->validate([
'email' => 'required|email',
'password' => 'required|min:6',
]);

if ($validation->fails()) {
return back()->withErrors($validation->getMessages());
}

$credentials = $request->only(['email', 'password']);

if (Auth::guard('web')->attempts($credentials)) {
return redirect('/dashboard');
}

return back()->withErrors(['message' => 'Email ou mot de passe incorrect']);
}

public function register(Request $request)
{
$validation = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|min:8|confirmed',
]);

if ($validation->fails()) {
return back()->withErrors($validation->getMessages());
}

$user = User::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => Hash::make($request->get('password')),
]);

$user->persist();

Auth::guard('web')->login($user);

return redirect('/dashboard');
}

public function logout()
{
Auth::guard('web')->logout();

return redirect('/login');
}
}

Routes​

routes/app.php
// Public pages
$app->get('/login', 'AuthController::showLogin');
$app->post('/login', 'AuthController::login');
$app->get('/register', 'AuthController::showRegister');
$app->post('/register', 'AuthController::register');
$app->post('/logout', 'AuthController::logout');

// Protected pages
$app->get('/dashboard', 'DashboardController::index')->middleware('auth');

Available methods​

MethodDescription
attempts($credentials)Attempts to authenticate with the credentials
check()Checks whether the user is logged in
guest()Checks whether the user is not logged in
user()Returns the authenticated user
id()Returns the user's ID
login($user)Manually logs a user in
logout()Logs the user out
getToken()(JWT) Returns the generated token
guard($name)Switches the guard

Is something missing?

If you run into problems with the documentation or have suggestions to improve the documentation or the project in general, please open an issue for us, or send a tweet mentioning the Twitter account @bowframework or directly on github.