0
0
Laravelframework~10 mins

API authentication with Sanctum in Laravel - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - API authentication with Sanctum
Client sends login request
Sanctum verifies credentials
Sanctum issues API token
Client stores token
Client sends API requests with token
Sanctum authenticates token
Server processes request or denies access
The client logs in, Sanctum checks credentials and gives a token. The client uses this token to access protected API routes, and Sanctum verifies the token each time.
Execution Sample
Laravel
Route::post('/login', function (Request $request) {
  $user = User::where('email', $request->email)->first();
  if (! $user || ! Hash::check($request->password, $user->password)) {
    return response()->json(['message' => 'Invalid credentials'], 401);
  }
  $token = $user->createToken('api-token')->plainTextToken;
  return response()->json(['token' => $token]);
});
This code logs in a user by checking email and password, then returns a JSON response with a Sanctum API token if valid.
Execution Table
StepActionInputCheck/ProcessOutput/Result
1Receive login request{email: 'user@example.com', password: 'secret'}Look up user by emailUser found with matching email
2Verify passwordPassword 'secret'Compare with stored hashPassword matches
3Create tokenUser objectGenerate new API tokenToken string generated
4Return tokenToken stringSend token in responseClient receives token
5Client sends API requestAPI request with token in headerSanctum checks token validityToken valid, request allowed
6Server processes requestValid tokenExecute API logicResponse data sent
7Client sends API requestAPI request with invalid tokenSanctum checks token validityToken invalid, access denied
8Return errorInvalid tokenSend 401 UnauthorizedClient receives error
💡 Execution stops when client receives token or access denied response.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 7
$requestN/A{email:'user@example.com', password:'secret'}{email:'user@example.com', password:'secret'}{email:'user@example.com', password:'secret'}{email:'user@example.com', password:'secret'}API request with tokenAPI request with invalid token
$usernullUser object foundUser object foundUser object foundUser object foundUser object foundUser object found
$tokennullnullnullToken string generatedToken string sentToken string sentnull
$responsenullnullnullnullJSON with tokenAPI response data401 Unauthorized error
Key Moments - 3 Insights
Why does Sanctum return a plain text token instead of a hashed one?
Sanctum returns a plain text token once so the client can store it. The server stores a hashed version for security. See execution_table step 3 and 4.
What happens if the password check fails?
The code returns a 401 Unauthorized response immediately, stopping token creation. See execution_sample code if condition.
How does Sanctum verify the token on API requests?
Sanctum checks the token sent in the request header against stored hashed tokens. If it matches, access is granted; otherwise, denied. See execution_table steps 5 to 8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 3?
AUser object found
BToken string generated
C401 Unauthorized error
DPassword mismatch
💡 Hint
Check the 'Output/Result' column at step 3 in the execution_table.
At which step does Sanctum deny access due to an invalid token?
AStep 7
BStep 6
CStep 5
DStep 4
💡 Hint
Look for 'Token invalid, access denied' in the execution_table.
If the password is wrong, what will the response be?
AToken string generated
BUser object found
C401 Unauthorized error
DAPI response data
💡 Hint
See the code in execution_sample, step 2 verification fails.
Concept Snapshot
API Authentication with Sanctum:
- Client sends login with email/password
- Server verifies credentials
- Server returns plain text API token
- Client uses token in Authorization header
- Sanctum verifies token on each API request
- Access granted if token valid, else 401 error
Full Transcript
This visual execution shows how Laravel Sanctum handles API authentication. First, the client sends a login request with email and password. The server looks up the user by email and checks the password. If correct, Sanctum creates a plain text API token and returns it to the client. The client stores this token and sends it with future API requests in the Authorization header. Sanctum verifies the token on each request. If the token is valid, the server processes the request and returns data. If invalid, Sanctum returns a 401 Unauthorized error. This flow ensures secure API access using tokens.