[Laravel 5.2 Document] Service--user authentication

Source: Internet
Author: User
Tags oauth oauth provider riak

1. Introduction

User authentication in Laravel is straightforward. In fact, almost everything has been configured for you. The configuration file is located in Config/auth.php, which contains a document-friendly option configuration for adjusting the behavior of the authentication service.

In the underlying code, Laravel's authentication component consists of "guards" and "providers", and Guard defines how the user authenticates in each request, for example, Laravel maintains the state of the session store through Sessionguard, Cookies as well as Tokenguard, Tokenguard is the "API token" with which the authenticated user sends the request.

Provider defines how to get the user information from the persisted storage, Laravel the underlying support to get the user through eloquent and the database Query Builder, and if necessary, you can define additional Provider.

If you see these nouns feel foggy, you don't have to worry too much, because for most applications, you just need to use the default authentication configuration and no changes are needed.

Database considerations

By default, Laravel contains a eloquent model App\user in the APP directory that can be used with the default eloquent authentication driver. If your app doesn't use eloquent, you can use the database authentication driver, which uses the Laravel query Builder.

When building a database table structure for the App\user model, make sure that the password field is at least 60 bits long.

Also, you should verify that the Users table contains a nullable, string-type remember_token field length of 100, which is used to store the "Remember Me" Session token that is maintained by the application, which can be used in the migration by using the $ Table->remembertoken (); to achieve.

2. Quick Start

Laravel provides two authentication controllers located in the App\http\controllers\auth namespace, Authcontroller handles new user registration and login, Passwordcontroller is used to help users recover their passwords. Each controller uses trait to introduce the methods they need. For many applications, you don't need to modify these two controllers at all.

Routing

Laravel can quickly generate the routes and views required for authentication by running the following command:

PHP Artisan Make:auth

Running this command generates the registration and login views, along with all authenticated routes, and generates HomeController, since the login succeeds and jumps to the action under the controller. Of course, you can also use this command to completely customize or remove the controller, depending on your application needs.

View

As mentioned above, the PHP artisan make:auth command Creates a view of all authentication needs in the Resources/views/auth directory.

The Make:auth command also creates the Resources/views/layouts directory, which contains the application's underlying layout files. All of these views use the Bootstrap CSS framework, and you can customize them as needed.

Certification

Now that you've set up Routing and views for your own authentication controller, let's implement new user registration and login certifications. You can access the defined routes in the browser, and the authentication controller already includes the registration and login logic (via trait) by default.

Custom Paths

Once a user has successfully logged in, the default will be to jump to/, you can customize the jump path after successful login by setting the Redirectto property in Authcontroller:

protected $redirectTo = ' home ';

When a user fails to log in, the default is to jump back to the page that corresponds to the login form.

Custom Guard

You can also customize the "guard" that implements user authentication, to achieve this, you need to define the Guard property in Authcontroller, which corresponds to the corresponding guard configuration in the authentication profile auth.php:

Protected $guard = ' admin ';

Custom Validation/storage

To modify the form fields that are required for new user registration, or to customize how new user fields are stored in the database, you can modify the Authcontroller class. This class is responsible for validating input parameters and creating new users for the app.

Authcontroller's Validator method contains validation rules for new users, and you can customize the method as needed.

The Create method of Authcontroller is responsible for creating new App\user records in the database using eloquent ORM. Of course, you can also customize the method based on your own needs.

Get Authenticated Users

You can access authenticated users through the auth façade:

$user = Auth::user ();

In addition, after the user has passed the authentication, you can also access the authenticated user through the Illuminate\http\request instance:

 
  User ()) {            //$request->user () returns the authenticated user instance ...}        }    

Determine if the current user is certified

To determine whether a user is logged in to the app, you can use the check method of the Auth façade, which returns true if the user passes authentication:

if (Auth::check ()) {    //the user is logged in ...}

In addition, you can use middleware to verify that a user is authenticated before accessing a specific route/controller, and to learn more, you can view the following route protection:

Routing protection

Routing middleware can be used to allow only authenticated users to access a given route. Laravel handles this by defining the AUTH middleware in app\http\middleware\authenticate.php. All you have to do is add the middleware to the appropriate route definition:

Use routing closures ... Route::get (' profile ', [' middleware ' = ' auth ', function () {    //Only Authenticated users can enter ...}]); /Use Controller ... Route::get (' profile ', [    ' middleware ' = ' auth ',    ' uses ' = ' profilecontroller@show ']);

Of course, if you are using a controller class, you can also call the middleware method in the controller's construction method instead of directly in the router:

Public Function __construct () {    $this->middleware (' auth ');}

Specify a guard

After adding auth middleware to routing, you also need to specify which guard to use for authentication:

Route::get (' profile ', [    ' middleware ' = ' auth:api ',    ' uses ' = ' profilecontroller@show ']);

The specified guard corresponds to a key in the guards array in the configuration file auth.php.

Number of logon failures limit

If you use the Laravel built-in Authcontroller class, you can use illuminate\foundation\auth\throttlesloginstrait to limit the number of user logon failures. By default, users will not be able to log in for a minute after a few login failures, based on the user's username/email address +IP address:

     

3, manually authenticated users

Of course, you can also not use Laravel's own authentication controller. If you choose to remove these controllers, you need to use the Laravel authentication class directly to manage user authentication. Don't worry, it's easy!

We will access the authentication service through the auth façade, so we need to make sure that the auth façade is imported at the top of the class, so let's look at the attempt method:

 
   $email, ' password ' = $password])) {            //certification passed ...            Return Redirect ()->intended (' Dashboard ');}}    

The attempt method receives an array of key values as the first parameter, and the values in the array are used to find the user from the data table, so in the example above, the user will get the value of the email, if the user is found, The password stored in the data after hashing is compared with the value of the hashed password that is passed over the hash operation. If the two hashed passwords match then an authentication session will be opened for the user.

If the authentication succeeds, the attempt method returns true. Otherwise, returns false.

The intended method on the redirector redirects the user to the URL that the user wants to access before logging in, and the alternate URI is passed to the method if the destination URL is not valid.

Specify additional conditions

If required, additional conditions can be added to the authentication query in addition to the user's mail and password, for example, we can verify that the user is marked as valid:

if (auth::attempt ([' email ' = = $email, ' password ' = ' + ' $password, ' active ' + 1])) {//the user is active, not Suspe Nded, and exists.}

Note: In these examples, it is not limited to using email for login authentication, just as a demo example, you can modify it to any other field in the database that is available as "username".

accessing the specified Guard instance

You can use the Guard method of the Auth façade to specify the guard instance you want to use, which allows you to achieve a completely independent user authentication for different authentication models or user tables in the same application.

The guard name passed to the guard method corresponds to a key configured in the Guards configuration file auth.php:

if (Auth::guard (' admin ')->attempt ($credentials)) {//}

Exit

To exit the app, you can use the logout method of the Auth façade, which clears the authentication information from the user Session:

Auth::logout ();

Remember users

If you want to provide "remember me" functionality in your app, you can pass a Boolean value as the second parameter to the attempt method, so that the user login authentication status will persist until they manually exit. Of course, your users table must contain the Remember_token field, which is used to store the "Remember Me" token.

if (auth::attempt ([' Email ' = $email, ' password ' + $password], $remember)} {    //the user is being remembered. .}

If you want to "remember" the user, you can use the Viaremember method to determine whether the user uses the "Remember Me" cookie for authentication:

if (Auth::viaremember ()) {    //}

Other authentication methods

Authenticating a User instance

If you need to log an existing user instance into the app, you can call the login method of the Auth façade and pass in the user instance, the incoming instance must be an implementation of the illuminate\contracts\auth\authenticatable contract, of course, The Laravel's own App\user model has implemented this interface:

Auth::login ($user);

Authenticate users by ID

To log in to an app with a user ID, you can use the Loginusingid method, which receives the primary key of the user you want to authenticate as a parameter:

Auth::loginusingid (1);

One-time Authenticated Users

You can use the once method to log users to the app only in a single request, without storing any sessions and cookies, which is useful when building stateless APIs. The once method and the attempt method use the same way:

if (Auth::once ($credentials)) {    //}

4. Basic authentication based on HTTP

HTTP Basic authentication can help users quickly implement login authentication without having to set up a dedicated login page, first to add Auth.basic middleware to the route. The middleware is Laravel, so you don't need to define it yourself:

Route::get (' profile ', [' middleware ' = ' auth.basic ', function () {    //Only Authenticated users can enter ...}]);

After the middleware is added to the route, when the route is accessed in the browser, the authentication information is automatically prompted, by default, the Auth.basic middleware uses the email field on the user record as the "username".

FastCGI, pay attention.

If you use PHP fastcgi,http Basic authentication will not work properly, you need to add the following to the. htaccess file:

Rewritecond%{http:authorization} ^ (. +) $RewriteRule. *-[E=http_authorization:%{http:authorization}]

Stateless HTTP Basic Authentication

Using HTTP Basic authentication also does not require a user identity Cookie to be set in Session, which is useful in API authentication. To implement this, you need to define a middleware that calls the Oncebasic method. If the method does not return any response, the request will continue to go:

      

Next, you register the routing middleware and add it to the route:

Route::get (' Api/user ', [' middleware ' = ' auth.basic.once ', function () {    //Only Authenticated users can enter ...}]);

5. Reset Password

Database considerations

Most Web apps provide the ability to reset passwords, and Laravel provides a convenient way to send password prompts and perform password resets without requiring you to re-implement them in each app.

Before you begin, verify that the App\user model implements the Illuminate\contracts\auth\canresetpassword contract. Of course, Laravel's own App\user model has implemented the interface and uses Illuminate\auth\passwords\canresetpasswordtrait to contain the methods needed to implement the interface.

Generate a Reset token table migration

Next, the table used to store the password reset token must be created, and Laravel has already migrated the table, which is stored in the Database/migrations directory. All, all you have to do is run the migration:

PHP Artisan Migrate

Routing

The Laravel comes with the Auth\passwordcontroller, which contains the appropriate logic to reset the user's password. The route required to reset the password has been automatically generated by the Make:auth command:

PHP Artisan Make:auth

View

As with routing, the view files required to reset the password are also generated by the Make:auth command, which is located in the Resources/views/auth/passwords directory and you can modify the resulting file as needed.

After resetting the password

After you have defined the Reset user password Routing and view, you only need to access these routes in the browser. The Passwordcontroller that comes with the framework already contains the logic to send a password reset linked message and to update the password in the database.

After the password is reset, the user will automatically log on to the app and redirect to/home. You can customize the jump link after a successful password reset by defining the Redirectto property on Passwordcontroller:

protected $redirectTo = '/dashboard ';

Note: By default, the password reset token is valid for an hour, and you can change the effective time by modifying the option Reminder.expire in the config/auth.php file.

Custom

Custom Authentication Guard

In profile auth.php, you can configure multiple "guards" to implement independent authentication for multi-user tables, and you can use the guard you choose by adding $guard properties to your own Passwordcontroller controller:

/*** The authentication guard that should is used.** @var string*/protected $guard = ' admins ';

Custom Password Broker

In profile auth.php, you can configure multiple passwords to be used to reset password broker for multiple user tables, and you can also use the broker that you select by adding the $broker property to the Passwordcontroller controller that comes with it:

/*** The password broker that should is used.** @var string*/protected $broker = ' admins ';

6. Social Login Authentication

Laravel can also use Laravel socialite to easily and easily authenticate with OAuth providers, social logins that currently support Facebook, Twitter, LinkedIn, GitHub and BitBucket for login authentication.

To use social logins, you need to add dependencies to the Composer.json file:

Composer require Laravel/socialite

Configuration

After installing the social login library, register Laravel\socialite\socialiteserviceprovider in the profile config/app.php:

' Providers ' = [    //Other service providers    ... Laravel\socialite\socialiteserviceprovider::class,],

Also add the socialite façade to the aliases array in the app configuration file:

' Socialite ' = Laravel\socialite\facades\socialite::class,

You'll also need to add authentication information for the OAuth service used by your app, located in Profile config/services.php, and with keys for Facebook, Twitter, LinkedIn, Google, GitHub or BitBucket, This depends on the provider that the application needs. For example:

' GitHub ' = [    ' client_id ' = ' your-github-app-id ',    ' client_secret ' = ' Your-github-app-secret ', '    redirect ' = ' Http://your-callback-url ',],

Basic use

Next, get ready to authenticate users! You need two routes: one to redirect the user to the OAuth provider, and another user to obtain the callback from the provider after authentication. We use the socialite façade to access the socialite:

 
    redirect ();    }    /**     * Get user information from GitHub.     *     * @return Response */public    function Handleprovidercallback ()    {        $user = socialite::d River (' GitHub ')->user ();        $user->token;    }}

The redirect method sends the user to the OAuth provider, which reads the request information and obtains the user information from the provider, and before redirecting the user, you can also use the scope method on the request to set the scope, which overrides all the scopes that already exist:

Return socialite::d River (' GitHub ')            ->scopes ([' Scope1 ', ' scope2 '])->redirect ();

Of course, you need to define the route to the controller method:

Route::get (' Auth/github ', ' auth\authcontroller@redirecttoprovider '); Route::get (' Auth/github/callback ', ' auth\authcontroller@handleprovidercallback ');

Get user Information

After you have a user instance, you can get more details about the user:

$user = socialite::d River (' GitHub ')->user ();//OAuth-Providers$token = $user->token;//OAuth one providers$ token = $user->token; $tokenSecret = $user->tokensecret;//all Providers$user->getid (); $user->getnickname (); $user->getname (); $user->getemail (); $user->getavatar ();

7. Add a custom Guard

You can define your own authentication guard through the Extend method of the Auth façade, which needs to be implemented in the boot method of a service provider:

       

As you can see in the above example, the closure callback passed to the Extend method needs to return the implementation instance of Illuminate\contracts\auth\guard, which contains some of the methods required for custom authentication guard.

Once you have defined your own authentication guard, you can use the word guard in the Guards configuration of the configuration file:

' Guards ' + [    ' api ' = ['        driver ' + ' JWT ',        ' provider ' and ' users ',    ],

8. Add a custom user provider

If you are not using a traditional relational database to store user information, you need to use your own authenticated user provider to extend the Laravel. We use the Provider method definition on the auth façade to customize the provider, and the service provider calls the provider method as follows:

        

After registering the user provider with the provider method, you can switch to the new user provider in the profile config/auth.php. First, in the configuration file, define a providers array that uses the new driver:

' Providers ' = [    ' users ' and ' = '        driver ' = ' Riak ',    ],

You can then use this provider in your guards configuration:

' Guards ' + [    ' web ' = [        ' driver ' = ' session ',        ' provider ' and ' users ',    ],],

Userprovider contract

The Illuminate\contracts\auth\userprovider implementation is only responsible for obtaining illuminate\contracts\auth\authenticatable implementations from the persistent storage system, such as MySQL, Riak and so on. These two interfaces allow the Laravel authentication mechanism to continue to function regardless of how the user data is stored or what class to display.

Let's look at the Illuminate\contracts\auth\userprovider contract first:

         

The Retrievebyid method typically gets a key that represents the user, such as the self-increment ID in MySQL data. The method gets and returns the AUTHENTICATABL implementation that matches the ID.

The Retrievebytoken function obtains the user by uniquely identifying and storing the "Remember Me" token in the Remember_token field. As with the previous method, the method also returns the AUTHENTICATABL implementation.

The Updateremembertoken method updates the $user remember_token field with the new $token, and the new token can be a newly generated token (the login is selected to "Remember Me" is successfully assigned) or null (user exits).

The Retrievebycredentials method obtains an array of authentication information passed to the Auth::attempt method when attempting to log on to the system. The method next goes to the underlying persistent storage system to query the user that matches the authentication information, which typically runs a query with a "where" condition ($credentials [' username ']). The method then returns the implementation of the userinterface. This method does not do any password verification and authentication.

The Validatecredentials method compares the given $user and $credentials to authenticate the user. For example, this method compares $user->getauthpassword () string and Hash::make-processed $credentials [' Password ']. This method validates only the user authentication information and returns a Boolean value.

Authenticatable contract

Now that we have explored every method on Userprovider, let's look at authenticatable. The provider should return the interface implementation from the Retrievebyid and Retrievebycredentials methods:

          

This interface is very simple, the Getauthidentifier method returns the user "primary key", in the MySQL background is the ID, Getauthpassword returns the hashed user password, this interface allows the authentication system to process any user class, whether you are using an ORM Or the storage abstraction layer. By default, the user class in the Laravel app directory implements this interface, so you can use this class as an implementation example.

9. Events

Laravel supports triggering multiple events during the authentication process, and you can listen to these events in your own Eventserviceprovider:

/** * The event listener mappings for the application. * * @var array */protected $listen = [    ' illuminate\auth\events\attempting ' = = [        ' app\listeners\ Logauthenticationattempt ',    ],    ' illuminate\auth\events\login ' = [        ' app\listeners\ Logsuccessfullogin ',    ],    ' illuminate\auth\events\logout ' = [        ' App\listeners\logsuccessfullogout ',    ],];
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.