Professional Documents
Culture Documents
Introduction
Database Considerations
Authentication Quickstart
Routing
Views
Authenticating
Retrieving The Authenticated User
Protecting Routes
Password Confirmation
Login Throttling
Manually Authenticating Users
Remembering Users
Other Authentication Methods
HTTP Basic Authentication
Introduction
{tip} Want to get started fast? Install the laravel/ui Composer
package and run php artisan ui vue --auth in a fresh Laravel
application. After migrating your database, navigate your browser
to http://your-app.test/register or any other URL that is
assigned to your application. These commands will take care of
scaffolding your entire authentication system!
Providers define how users are retrieved from your persistent storage.
Laravel ships with support for retrieving users using Eloquent and the
database query builder. However, you are free to define additional
providers as needed for your application.
Don't worry if this all sounds confusing now! Many applications will
never need to modify the default authentication configuration.
Database Considerations
By default, Laravel includes an App\User Eloquent model in your app
directory. This model may be used with the default Eloquent
authentication driver. If your application is not using Eloquent, you
may use the database authentication driver which uses the Laravel
query builder.
When building the database schema for the App\User model, make
sure the password column is at least 60 characters in length.
Maintaining the default string column length of 255 characters would
be a good choice.
Also, you should verify that your users (or equivalent) table contains
a nullable, string remember_token column of 100 characters. This
column will be used to store a token for users that select the
"remember me" option when logging into your application.
Authentication Quickstart
Routing
Laravel's laravel/ui package provides a quick way to scaffold all of
the routes and views you need for authentication using a few simple
commands:
Views
As mentioned in the previous section, the laravel/ui package's php
artisan ui vue --auth command will create all of the views you need
for authentication and place them in the resources/views/auth
directory.
Authenticating
Now that you have routes and views setup for the included
authentication controllers, you are ready to register and authenticate
new users for your application! You may access your application in a
browser since the authentication controllers already contain the logic
(via their traits) to authenticate existing users and store new users in
the database.
Path Customization
When a user is successfully authenticated, they will be redirected to
the /home URI. You can customize the post-authentication redirect
path using the HOME constant defined in your
RouteServiceProvider :
1 /**
2 * The user has been authenticated.
3 *
4 * @param \Illuminate\Http\Request $request
5 * @param mixed $user
6 * @return mixed
7 */
8 protected function authenticated(Request $request,
$user)
9 {
10 return response([
11 //
12 ]);
13 }
Username Customization
By default, Laravel uses the email field for authentication. If you
would like to customize this, you may define a username method on
your LoginController :
Guard Customization
You may also customize the "guard" that is used to authenticate and
register users. To get started, define a guard method on your
LoginController , RegisterController , and
ResetPasswordController . The method should return a guard
instance:
1 use Illuminate\Support\Facades\Auth;
2
3 protected function guard()
4 {
5 return Auth::guard('guard-name');
6 }
1 use Illuminate\Support\Facades\Auth;
2
3 // Get the currently authenticated user...
4 $user = Auth::user();
5
6 // Get the currently authenticated user's ID...
7 $id = Auth::id();
1 use Illuminate\Support\Facades\Auth;
2
3 if (Auth::check()) {
4 // The user is logged in...
5 }
1 Route::get('profile', function () {
2 // Only authenticated users may enter...
3 })->middleware('auth');
If you are using controllers, you may call the middleware method
from the controller's constructor instead of attaching it in the route
definition directly:
1 /**
2 * Get the path the user should be redirected to.
3 *
4 * @param \Illuminate\Http\Request $request
5 * @return string
6 */
7 protected function redirectTo($request)
8 {
9 return route('login');
10 }
Specifying A Guard
When attaching the auth middleware to a route, you may also specify
which guard should be used to authenticate the user. The guard
specified should correspond to one of the keys in the guards array of
your auth.php configuration file:
Password Confirmation
Sometimes, you may wish to require the user to confirm their
password before accessing a specific area of your application. For
example, you may require this before the user modifies any billing
settings within the application.
1 Route::get('/settings/security', function () {
2 // Users must confirm their password before
continuing...
3 })->middleware(['auth', 'password.confirm']);
After the user has successfully confirmed their password, the user is
redirected to the route they originally tried to access. By default, after
confirming their password, the user will not have to confirm their
password again for three hours. You are free to customize the length
of time before the user must re-confirm their password using the
auth.password_timeout configuration option.
Login Throttling
If you are using Laravel's built-in LoginController class, the
Illuminate\Foundation\Auth\ThrottlesLogins trait will already be
included in your controller. By default, the user will not be able to
login for one minute if they fail to provide the correct credentials after
several attempts. The throttling is unique to the user's username / e-
mail address and their IP address.
1 <?php
2
3 namespace App\Http\Controllers;
4
5 use Illuminate\Http\Request;
6 use Illuminate\Support\Facades\Auth;
7
8 class LoginController extends Controller
9 {
10 /**
11 * Handle an authentication attempt.
12 *
13 * @param \Illuminate\Http\Request $request
14 *
15 * @return Response
16 */
17 public function authenticate(Request $request)
18 {
19 $credentials = $request->only('email',
'password');
20
21 if (Auth::attempt($credentials)) {
22 // Authentication passed...
23 return redirect()->intended('dashboard');
24 }
25 }
26 }
The attempt method accepts an array of key / value pairs as its first
argument. The values in the array will be used to find the user in your
database table. So, in the example above, the user will be retrieved by
the value of the email column. If the user is found, the hashed
password stored in the database will be compared with the password
value passed to the method via the array. You should not hash the
password specified as the password value, since the framework will
automatically hash the value before comparing it to the hashed
password in the database. If the two hashed passwords match an
authenticated session will be started for the user.
The intended method on the redirector will redirect the user to the
URL they were attempting to access before being intercepted by the
authentication middleware. A fallback URI may be given to this
method in case the intended destination is not available.
You may specify which guard instance you would like to utilize using
the guard method on the Auth facade. This allows you to manage
authentication for separate parts of your application using entirely
separate authenticatable models or user tables.
1 if (Auth::guard('admin')->attempt($credentials)) {
2 //
3 }
Logging Out
To log users out of your application, you may use the logout method
on the Auth facade. This will clear the authentication information in
the user's session:
1 Auth::logout();
Remembering Users
If you would like to provide "remember me" functionality in your
application, you may pass a boolean value as the second argument to
the attempt method, which will keep the user authenticated
indefinitely, or until they manually logout. Your users table must
include the string remember_token column, which will be used to
store the "remember me" token.
1 if (Auth::viaRemember()) {
2 //
3 }
If you need to log an existing user instance into your application, you
may call the login method with the user instance. The given object
must be an implementation of the
Illuminate\Contracts\Auth\Authenticatable contract. The
App\User model included with Laravel already implements this
interface:
1 Auth::login($user);
2
3 // Login and "remember" the given user...
4 Auth::login($user, true);
You may specify the guard instance you would like to use:
1 Auth::guard('admin')->login($user);
Authenticate A User By ID
To log a user into the application by their ID, you may use the
loginUsingId method. This method accepts the primary key of the
user you wish to authenticate:
1 Auth::loginUsingId(1);
2
3 // Login and "remember" the given user...
4 Auth::loginUsingId(1, true);
Authenticate A User Once
You may use the once method to log a user into the application for a
single request. No sessions or cookies will be utilized, which means
this method may be helpful when building a stateless API:
1 if (Auth::once($credentials)) {
2 //
3 }
1 Route::get('profile', function () {
2 // Only authenticated users may enter...
3 })->middleware('auth.basic');
Once the middleware has been attached to the route, you will
automatically be prompted for credentials when accessing the route
in your browser. By default, the auth.basic middleware will use the
email column on the user record as the "username".
A Note On FastCGI
If you are using PHP FastCGI, HTTP Basic authentication may not work
correctly out of the box. The following lines should be added to your
.htaccess file:
1 <?php
2
3 namespace App\Http\Middleware;
4
5 use Illuminate\Support\Facades\Auth;
6
7 class AuthenticateOnceWithBasicAuth
8 {
9 /**
10 * Handle an incoming request.
11 *
12 * @param \Illuminate\Http\Request $request
13 * @param \Closure $next
14 * @return mixed
15 */
16 public function handle($request, $next)
17 {
18 return Auth::onceBasic() ?: $next($request);
19 }
20
21 }
1 Route::get('api/user', function () {
2 // Only authenticated users may enter...
3 })->middleware('auth.basic.once');
Logging Out
To manually log users out of your application, you may use the
logout method on the Auth facade. This will clear the authentication
information in the user's session:
1 use Illuminate\Support\Facades\Auth;
2
3 Auth::logout();
1 'web' => [
2 // ...
3
\Illuminate\Session\Middleware\AuthenticateSession::cla
ss,
4 // ...
5 ],
1 use Illuminate\Support\Facades\Auth;
2
3 Auth::logoutOtherDevices($password);
1 <?php
2
3 namespace App\Providers;
4
5 use App\Services\Auth\JwtGuard;
6 use
Illuminate\Foundation\Support\Providers\AuthServicePro
vider as ServiceProvider;
7 use Illuminate\Support\Facades\Auth;
8
9 class AuthServiceProvider extends ServiceProvider
10 {
11 /**
12 * Register any application authentication /
authorization services.
13 *
14 * @return void
15 */
16 public function boot()
17 {
18 $this->registerPolicies();
19
20 Auth::extend('jwt', function ($app, $name,
array $config) {
21 // Return an instance of
Illuminate\Contracts\Auth\Guard...
22
23 return new
JwtGuard(Auth::createUserProvider($config['provider'])
);
24 });
25 }
26 }
As you can see in the example above, the callback passed to the
extend method should return an implementation of
Illuminate\Contracts\Auth\Guard . This interface contains a few
methods you will need to implement to define a custom guard. Once
your custom guard has been defined, you may use this guard in the
guards configuration of your auth.php configuration file:
1 'guards' => [
2 'api' => [
3 'driver' => 'jwt',
4 'provider' => 'users',
5 ],
6 ],
1 use App\User;
2 use Illuminate\Http\Request;
3 use Illuminate\Support\Facades\Auth;
4
5 /**
6 * Register any application authentication /
authorization services.
7 *
8 * @return void
9 */
10 public function boot()
11 {
12 $this->registerPolicies();
13
14 Auth::viaRequest('custom-token', function
($request) {
15 return User::where('token', $request->token)-
>first();
16 });
17 }
Once your custom authentication driver has been defined, you use it
as a driver within guards configuration of your auth.php
configuration file:
1 'guards' => [
2 'api' => [
3 'driver' => 'custom-token',
4 ],
5 ],
1 <?php
2
3 namespace App\Providers;
4
5 use App\Extensions\RiakUserProvider;
6 use
Illuminate\Foundation\Support\Providers\AuthServicePro
vider as ServiceProvider;
7 use Illuminate\Support\Facades\Auth;
8
9 class AuthServiceProvider extends ServiceProvider
10 {
11 /**
12 * Register any application authentication /
authorization services.
13 *
14 * @return void
15 */
16 public function boot()
17 {
18 $this->registerPolicies();
19
20 Auth::provider('riak', function ($app, array
$config) {
21 // Return an instance of
Illuminate\Contracts\Auth\UserProvider...
22
23 return new RiakUserProvider($app-
>make('riak.connection'));
24 });
25 }
26 }
After you have registered the provider using the provider method,
you may switch to the new user provider in your auth.php
configuration file. First, define a provider that uses your new driver:
1 'providers' => [
2 'users' => [
3 'driver' => 'riak',
4 ],
5 ],
1 <?php
2
3 namespace Illuminate\Contracts\Auth;
4
5 interface UserProvider
6 {
7 public function retrieveById($identifier);
8 public function retrieveByToken($identifier,
$token);
9 public function
updateRememberToken(Authenticatable $user, $token);
10 public function retrieveByCredentials(array
$credentials);
11 public function
validateCredentials(Authenticatable $user, array
$credentials);
12 }
The retrieveById function typically receives a key representing the
user, such as an auto-incrementing ID from a MySQL database. The
Authenticatable implementation matching the ID should be
retrieved and returned by the method.
Events
Laravel raises a variety of events during the authentication process.
You may attach listeners to these events in your
EventServiceProvider :
1 /**
2 * The event listener mappings for the application.
3 *
4 * @var array
5 */
6 protected $listen = [
7 'Illuminate\Auth\Events\Registered' => [
8 'App\Listeners\LogRegisteredUser',
9 ],
10
11 'Illuminate\Auth\Events\Attempting' => [
12 'App\Listeners\LogAuthenticationAttempt',
13 ],
14
15 'Illuminate\Auth\Events\Authenticated' => [
16 'App\Listeners\LogAuthenticated',
17 ],
18
19 'Illuminate\Auth\Events\Login' => [
20 'App\Listeners\LogSuccessfulLogin',
21 ],
22
23 'Illuminate\Auth\Events\Failed' => [
24 'App\Listeners\LogFailedLogin',
25 ],
26
27 'Illuminate\Auth\Events\Logout' => [
28 'App\Listeners\LogSuccessfulLogout',
29 ],
30
31 'Illuminate\Auth\Events\Lockout' => [
32 'App\Listeners\LogLockout',
33 ],
34
35 'Illuminate\Auth\Events\PasswordReset' => [
36 'App\Listeners\LogPasswordReset',
37 ],
38 ];