An AuthController manages the lifecycle of a JWT session. Key operations include:
- Login: Validates credentials using
auth()->attempt($credentials) and returns a token. - Logout: Invalidates the current token using
auth()->logout(). - Refresh: Issues a new token using
auth()->refresh(). - Me: Retrieves the currently authenticated user via
auth()->user().
When protecting routes, use the auth:api middleware. You can exclude the login method from this middleware to allow users to authenticate.
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
public function me()
{
return response()->json(auth()->user());
}
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}