Authentication Enhancements in Laravel 5.3 – Sponsor

Published on by

Authentication Enhancements in Laravel 5.3 – Sponsor image

TLDR Laravel 5.3 was released at the recently concluded LaraconEU conference. Laravel 5.3 ships with a lot of new features and awesome improvements to different sections of already existing features. Authentication is one of those features that Laravel provides to developers out of the box and there have been some really good improvements to it in Laravel 5.3. In this post, I’ll walk you through these enhancements and how you can savor this goodness in your applications!

The following are the top 6 authentication enhancements in Laravel 5.3:

#1. Better authentication response handling: In Laravel 5.2, you have to write more code to handle unauthenticated users, especially when you are writing custom logic for authentication. In Laravel 5.3, all you need to use is the new authenticate method. This is a simple illustration below:

The authenticate method simply throws a global AuthenticationException that Laravel catches and handle if the user is not logged in. Check your app/Exceptions/Handler.php , there is an unauthenticated method that is fired when the AuthenticationException is thrown. You can simply customize the redirect page or json response in this single location as shown in the image below:

#2. Authenticate Middleware moved to core: In Laravel 5.2, four middleware files are shipped with the new app skeleton. In Laravel 5.3, only three middleware files are shipped with your app skeleton. The Authenticate middleware has been moved into Laravel core, thus forcing developers to make response customizations in the unauthenticated method of the app/Exceptions/Handler.php file.

#3. Multiple guard authentication in auth middleware: You already have guards in your application, e.g, the web and api guards. The auth middleware can now automagically check any of those guards passed to it — the request will be authenticated and the guard used by the admin user (can be any user) will be set as default, so that subsequent calls to auth()->user() will return the user details.

Route::get('admin', [
'uses' => 'AdminController@index',
'Middleware' => 'auth:web,api'
]);

#4. Guard customization: In Laravel 5.2, you could customize the guard that is used to authenticate users by defining a guard property on your AuthController and assigning one of the guards configured in your auth.php config file like so:

Laravel 5.2

protected $guard = ‘api’;

In Laravel 5.3, you have to define a guard method on your LoginController, RegisterController and ResetPasswordController like so:

Laravel 5.3

use Illuminate\Support\Facades\Auth;
 
protected function guard()
{
return Auth:guard('name-of-guard');
}

#5. Global scopes and Route Model binding: In Laravel 5.2, if you are using route model binding and you have a global scope on your model that needs access to the current user via the auth() helper method or Auth facade, the current user returns null. Why? Because the route model binding runs before the authentication middleware is invoked thus making the model impossible to resolve the current logged-in user. An illustration is shown below:

//ProjectController.php
public function show()
{
// display the project
}
 
// Project.php - Model
class Project extends Model
{
protected static function boot()
{
static::addGlobalScope(function ($query) {
$query->where(‘written_by’, auth()->email);
});
}
}
 
// routes.php
Route::get('projects/{project}', [
'uses' => 'ProjectController@show',
'middleware' => 'auth',
]);

In Laravel 5.3, the current logged-in user can now be obtained in your global scopes because the middleware stack has been rewritten in a way that the authentication middleware will always run before the route model binding!

#6. App Authentication Skeleton ships with four controllers: In Laravel 5.2, only two authentication controllers are shipped out of the box, AuthController (handles user registration and authentication) and PasswordController (handles resetting users forgotten passwords). In Laravel 5.3, there are now four authentication controllers:

  • ForgotPasswordController – handles e-mailing links for resetting passwords,
  • LoginController – handles authentication,
  • RegisterController – handles new user registration,
  • ResetPasswordController – handles resetting user passwords

Each of these controllers has its own traits. I really like how the controllers are split right now, this encourages separation of concerns and single responsibility patterns in Object-Oriented PHP programming.

A lot of work has also gone into enhancing the already existing authorization techniques. Joseph Silber has got them covered here.

Note: If you are new to Laravel and want to get your hands dirty with creating your first app, check out https://auth0.com/blog/creating-your-first-laravel-app-and-adding-authentication/

Aside: Using Auth0 with Laravel

Auth0 issues JSON Web Tokens on every login for your users. This means that you can have a solid identity infrastructure, including single sign-on, user management, support for social identity providers (Facebook, Github, Twitter, etc.), enterprise identity providers (Active Directory, LDAP, SAML, etc.) and your own database of users with just a few lines of code.

We can easily set up authentication in our Laravel apps by using the Lock Widget. If you don’t already have an Auth0 account, you can sign up for one now. Navigate to the Auth0 management dashboard, select Applications from the navigational menu, then select the app you want to connect with Laravel.

There is a comprehensive quickstart for laravel-auth0 webapp and RESTful API integration that can walk you through setting it up in less than three minutes!

Auth0 Lock Widget

With Auth0, you can have all your users information stored without having to run your own database. You can configure the Lock UI, which provides powerful analytics about users signing up on your platform such as, the browser the user logged in with, the location, device, number of logins, and more, out of the box!

Analytics

Auth0 also offers a cool feature called password breach protection. With breached password detection, you can protect your users and services from password leaks that occur on third party sites. The feature notifies your end-user that their password has been compromised somewhere else and you can optionally require step-up authentication or prevent that login until they reset their password.

Password breach protection

Conclusion

Authentication and authorization are powerful features of every application. Not getting it right means opening yourself and your firm to potential financial and reputation loss as well as lawsuits. You can check the laravel docs and source code to get to know a lot more about how authentication and authorization work in Laravel 5.3.

Lastly, if you want to add authentication to your Laravel apps in a breeze, Try Auth0 for free. You will get a production ready account with up to 7000 active users! Instead of worrying about your authentication component’s implementation details, testing, bugs, and extensibility, you can just focus on your application’s business logic.


Many thanks to Auth0 for sponsoring this tutorial via Syndicate Ads.

Eric L. Barnes photo

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Visit Paragraph
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Non-backed Enums in Database Queries and a withSchedule() bootstrap method in Laravel 11.1 image

Non-backed Enums in Database Queries and a withSchedule() bootstrap method in Laravel 11.1

Read article
Laravel Pint --bail Flag image

Laravel Pint --bail Flag

Read article
Laravel Herd for Windows is now released! image

Laravel Herd for Windows is now released!

Read article
The Laravel Worldwide Meetup is Today image

The Laravel Worldwide Meetup is Today

Read article
Cache Routes with Cloudflare in Laravel image

Cache Routes with Cloudflare in Laravel

Read article
Learn how to manage timezones in your Laravel Apps image

Learn how to manage timezones in your Laravel Apps

Read article