resolve()는 config/auth.php의 guards 배열에서 driver 키를 읽어 대응하는 팩토리 클로저를 호출합니다. 기본 제공되는 session이나 token 드라이버도 동일한 구조로 등록되어 있습니다.
Guard 인터페이스와 StatefulGuard 인터페이스의 차이
Laravel 인증 가드는 최소한 Illuminate\Contracts\Auth\Guard를 구현해야 합니다. 세션을 유지해야 하는 경우에는 StatefulGuard를 구현합니다.
Guard 인터페이스(Illuminate\Contracts\Auth\Guard)
interface Guard{ // 인증된 사용자가 존재하는지 확인 public function check(); // 게스트(미인증) 여부 확인 public function guest(); // 현재 인증된 사용자를 반환(미인증이면 null) public function user(); // 현재 인증된 사용자의 ID를 반환 public function id(); // 주어진 자격 증명이 유효한지 확인(로그인은 수행하지 않음) public function validate(array $credentials = []); // 사용자가 설정되어 있는지 확인(미로그인 상태에서도 setUser로 주입 가능) public function hasUser(); // 인증된 사용자를 수동으로 설정 public function setUser(Authenticatable $user);}
StatefulGuard는 Guard를 상속하며, 세션이나 쿠키를 사용한 로그인 상태 유지에 필요한 메서드를 추가합니다.
interface StatefulGuard extends Guard{ // 자격 증명을 검증하고 로그인(remember 플래그 포함) public function attempt(array $credentials = [], $remember = false); // 세션을 저장하지 않고 1개의 요청에서만 인증 public function once(array $credentials = []); // 사용자 인스턴스를 직접 로그인 public function login(Authenticatable $user, $remember = false); // ID를 지정하여 로그인 public function loginUsingId($id, $remember = false); // ID를 지정하여 1개의 요청에서만 인증 public function onceUsingId($id); // "로그인 상태 유지" 쿠키로 로그인했는지 확인 public function viaRemember(); // 로그아웃 public function logout();}
API 인증이나 자체 토큰 인증처럼 세션이 필요하지 않은 가드는 Guard만 구현하면 됩니다. 관리자 로그인처럼 세션이 필요한 경우에는 StatefulGuard를 구현합니다.
커스텀 가드 구현
GuardHelpers 트레이트
Guard 인터페이스의 check(), guest(), id(), hasUser()는 대부분 공통된 구현이 되기 때문에, Laravel은 Illuminate\Auth\GuardHelpers 트레이트를 제공합니다. 이 트레이트를 사용하면 필수 구현을 user()와 validate() 두 메서드로 줄일 수 있습니다.
// GuardHelpers가 제공하는 기본 구현(발췌)trait GuardHelpers{ protected $user; public function check(): bool { return ! is_null($this->user()); } public function guest(): bool { return ! $this->check(); } public function id(): mixed { return $this->user()?->getAuthIdentifier(); } public function hasUser(): bool { return ! is_null($this->user); } public function setUser(Authenticatable $user): static { $this->user = $user; return $this; }}
API 토큰 인증 가드 구현 예제
TokenGuard의 설계를 참고하여 간단한 API 토큰 인증 가드를 구현합니다. 요청 헤더 또는 쿼리 파라미터에서 토큰을 가져와 UserProvider를 통해 사용자를 해석합니다.
1
가드 클래스 생성
app/Auth 디렉터리에 가드 클래스를 생성합니다.
<?phpnamespace App\Auth;use Illuminate\Auth\GuardHelpers;use Illuminate\Contracts\Auth\Guard;use Illuminate\Contracts\Auth\UserProvider;use Illuminate\Http\Request;class ApiTokenGuard implements Guard{ use GuardHelpers; protected Request $request; public function __construct(UserProvider $provider, Request $request) { $this->provider = $provider; $this->request = $request; } /** * 현재 인증된 사용자를 반환 */ public function user(): ?\Illuminate\Contracts\Auth\Authenticatable { // 캐시된 사용자가 있다면 반환 if (! is_null($this->user)) { return $this->user; } $token = $this->getTokenForRequest(); if (empty($token)) { return null; } // UserProvider를 통해 사용자 조회 $this->user = $this->provider->retrieveByCredentials([ 'api_token' => $token, ]); return $this->user; } /** * 자격 증명 검증만 수행(로그인은 하지 않음) */ public function validate(array $credentials = []): bool { if (empty($credentials['api_token'])) { return false; } return (bool) $this->provider->retrieveByCredentials($credentials); } /** * 요청에서 토큰을 가져옴 * * 우선순위: Bearer 헤더 → 쿼리 파라미터 → 요청 바디 */ protected function getTokenForRequest(): ?string { $token = $this->request->bearerToken(); if (empty($token)) { $token = $this->request->query('api_token'); } if (empty($token)) { $token = $this->request->input('api_token'); } return $token ?: null; } /** * 요청 인스턴스를 교체 */ public function setRequest(Request $request): static { $this->request = $request; return $this; }}
2
서비스 프로바이더에서 가드 등록
AppServiceProvider의 boot() 메서드에서 Auth::extend()를 사용해 가드를 등록합니다.
<?phpnamespace App\Providers;use App\Auth\ApiTokenGuard;use Illuminate\Contracts\Foundation\Application;use Illuminate\Support\Facades\Auth;use Illuminate\Support\ServiceProvider;class AppServiceProvider extends ServiceProvider{ public function boot(): void { Auth::extend('api-token', function (Application $app, string $name, array $config) { // Auth::createUserProvider()로 config의 provider를 해석 $provider = Auth::createUserProvider($config['provider'] ?? 'users'); return new ApiTokenGuard($provider, $app->make('request')); }); }}
Auth::createUserProvider()는 config/auth.php의 providers 설정을 읽어 해당하는 UserProvider 인스턴스를 반환합니다. 커스텀 프로바이더를 만들지 않는 한, 이 호출 방식으로 기본 EloquentUserProvider를 사용할 수 있습니다.