Bird
Raised Fist0
Laravelframework~20 mins

Authentication guards in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Authentication Guard Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a user tries to access a route protected by the 'auth' guard without being logged in?

Consider a Laravel route protected by the default 'auth' guard. What is the behavior when an unauthenticated user tries to access this route?

Laravel
Route::middleware('auth')->get('/dashboard', function () {
    return 'Dashboard';
});
AThe user sees a 404 Not Found error.
BThe user is redirected to the login page automatically.
CThe user can access the route without restrictions.
DThe application throws a server error (500).
Attempts:
2 left
💡 Hint

Think about what Laravel does when authentication fails on routes protected by 'auth' middleware.

📝 Syntax
intermediate
2:00remaining
Which code snippet correctly defines a custom guard in Laravel's auth configuration?

Given the need to add a custom guard named 'admin' using the 'session' driver and 'admins' provider, which option is correct?

A"admin" => ["driver" => "token", "provider" => "admins"]
B"admin" => ["driver" => "session"]
C"admin" => ["provider" => "admins", "driver" => "session"]
D"admin" => ["driver" => "session", "provider" => "admins"]
Attempts:
2 left
💡 Hint

Remember the order of keys does not matter, but all required keys must be present.

🔧 Debug
advanced
2:30remaining
Why does the following code throw an error when trying to authenticate with a custom guard?

Examine this Laravel controller snippet:

if (Auth::guard('admin')->attempt(['email' => $email, 'password' => $password])) {
    return redirect()->intended('/admin/dashboard');
}

The error says: Call to undefined method attempt() on null. What is the cause?

AThe 'attempt' method does not exist on any guard in Laravel.
BThe 'email' and 'password' keys are incorrect; they should be 'username' and 'pass'.
CThe 'admin' guard is not defined in config/auth.php, so Auth::guard('admin') returns null.
DThe Auth facade is not imported, causing the method call to fail.
Attempts:
2 left
💡 Hint

Check if the guard name matches the configuration.

🧠 Conceptual
advanced
2:30remaining
What is the main difference between 'session' and 'token' drivers in Laravel authentication guards?

Laravel supports multiple drivers for authentication guards. What is the key difference between the 'session' and 'token' drivers?

A'session' driver uses cookies to maintain login state, while 'token' driver uses API tokens for stateless authentication.
B'session' driver is for API authentication, and 'token' driver is for web sessions.
C'session' driver requires manual token management, 'token' driver automatically manages sessions.
D'session' driver encrypts passwords, 'token' driver does not.
Attempts:
2 left
💡 Hint

Think about how web apps keep users logged in versus how APIs authenticate requests.

❓ state_output
expert
3:00remaining
What is the value of Auth::guard('web')->user() after logging in with a custom user provider?

Assume you have a custom user provider configured for the 'web' guard that fetches users from a special table. After a successful login, what does Auth::guard('web')->user() return?

AAn instance of the user model returned by the custom provider representing the logged-in user.
BNull, because custom providers do not support the user() method.
CA boolean true indicating successful authentication.
DAn array of all users in the custom table.
Attempts:
2 left
💡 Hint

Consider what the user() method returns after authentication.

Practice

(1/5)
1. What is the main purpose of an authentication guard in Laravel?
easy
A. To manage session timeouts
B. To store user passwords securely
C. To define database connections
D. To control how users are authenticated for each request

Solution

  1. Step 1: Understand the role of authentication guards

    Guards determine how users are authenticated on each request, like checking credentials or tokens.
  2. Step 2: Differentiate guards from other features

    Guards do not store passwords, manage sessions, or define databases; those are handled elsewhere.
  3. Final Answer:

    To control how users are authenticated for each request -> Option D
  4. Quick Check:

    Authentication guard = controls user authentication [OK]
Hint: Guards decide how users log in and access app [OK]
Common Mistakes:
  • Confusing guards with password storage
  • Thinking guards manage database connections
  • Assuming guards handle session timeouts
2. Which of the following is the correct way to specify a guard in Laravel's auth.php config file?
easy
A. 'guards' => ['web' => ['driver' => 'database', 'provider' => 'users']]
B. 'guards' => ['web' => ['driver' => 'token', 'provider' => 'admins']]
C. 'guards' => ['web' => ['driver' => 'session', 'provider' => 'users']]
D. 'guards' => ['api' => ['driver' => 'session', 'provider' => 'users']]

Solution

  1. Step 1: Check the standard guard configuration

    Laravel's default 'web' guard uses 'session' driver and 'users' provider.
  2. Step 2: Validate driver and provider correctness

    'database' is not a valid driver for guards; 'token' is used for API guards, but 'web' uses 'session'.
  3. Final Answer:

    'guards' => ['web' => ['driver' => 'session', 'provider' => 'users']] -> Option C
  4. Quick Check:

    Default web guard uses session driver [OK]
Hint: Web guard uses session driver and users provider [OK]
Common Mistakes:
  • Using 'database' as a driver instead of 'session'
  • Mixing 'token' driver with 'web' guard
  • Assigning wrong provider names
3. Given this code snippet in a Laravel controller:
if (Auth::guard('admin')->check()) {
    return 'Admin logged in';
} else {
    return 'No admin logged in';
}

What will be the output if no admin user is logged in but a regular user is?
medium
A. No admin logged in
B. Error: guard not found
C. Admin logged in
D. No output

Solution

  1. Step 1: Understand what Auth::guard('admin')->check() does

    This checks if a user is logged in using the 'admin' guard specifically.
  2. Step 2: Analyze the scenario

    No admin user is logged in, so check() returns false, even if a regular user is logged in under a different guard.
  3. Final Answer:

    No admin logged in -> Option A
  4. Quick Check:

    Guard check false means no user logged in for that guard [OK]
Hint: Guard check only sees users of that guard [OK]
Common Mistakes:
  • Assuming any logged-in user passes the guard check
  • Confusing guard names
  • Expecting error if guard exists
4. Identify the error in this Laravel guard usage:
Auth::guard('web')->login($user);
if (Auth::check()) {
    return 'User logged in';
}
medium
A. No error, code works correctly
B. Auth::check() does not check the 'web' guard by default
C. Missing middleware to protect the route
D. Auth::guard('web')->login() requires a user ID, not a user object

Solution

  1. Step 1: Understand Auth::guard('web')->login()

    This logs in the user using the 'web' guard explicitly.
  2. Step 2: Check what Auth::check() does

    Auth::check() uses the default guard, which may not be 'web', so it might not detect the login.
  3. Final Answer:

    Auth::check() does not check the 'web' guard by default -> Option B
  4. Quick Check:

    Auth::check() uses default guard, not necessarily 'web' [OK]
Hint: Auth::check() uses default guard, not specified guard [OK]
Common Mistakes:
  • Assuming Auth::check() checks all guards
  • Thinking login() needs user ID only
  • Ignoring middleware importance
5. You want to protect an admin route so only users authenticated with the 'admin' guard can access it. Which is the correct way to apply this in Laravel's route definition?
hard
A. Route::middleware('auth:admin')->group(function () { Route::get('/admin', fn() => 'Admin area'); });
B. Route::middleware('auth:web')->group(function () { Route::get('/admin', fn() => 'Admin area'); });
C. Route::middleware('guest:admin')->group(function () { Route::get('/admin', fn() => 'Admin area'); });
D. Route::middleware('auth')->group(function () { Route::get('/admin', fn() => 'Admin area'); });

Solution

  1. Step 1: Understand middleware usage for guards

    The 'auth' middleware accepts a guard name to specify which guard to check for authentication.
  2. Step 2: Choose the middleware that checks 'admin' guard

    'auth:admin' ensures only users authenticated with 'admin' guard access the route.
  3. Step 3: Eliminate incorrect options

    'auth:web' checks the wrong guard, 'guest:admin' checks for unauthenticated users, and 'auth' without guard uses default guard.
  4. Final Answer:

    Route::middleware('auth:admin')->group(function () { Route::get('/admin', fn() => 'Admin area'); }); -> Option A
  5. Quick Check:

    Use 'auth:guardname' middleware to protect routes [OK]
Hint: Use 'auth:admin' middleware to protect admin routes [OK]
Common Mistakes:
  • Using 'auth' without specifying guard
  • Using 'guest' middleware instead of 'auth'
  • Applying wrong guard name in middleware
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard