How To Create Manually Authentication Secure In Laravel

admin_img Posted By Bajarangi soft , Posted On 18-09-2020

We can do manual authentication for the users by using auth façade.It includes the attempt method to verify their email and password.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.

How To Create Manually Authentication Secure In Laravel

Note that you are not required to use the authentication controllers included with Laravel. If you choose to remove these controllers, you will need to manage user authentication using the Laravel authentication classes directly. Don't worry, it's a cinch!

We will access Laravel's authentication services via the Auth facade, so we'll need to make sure to import the Auth facade at the top of the class. Next, let's check out the attempt method:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * Handle an authentication attempt.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return Response
     */
    public function authenticate(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        }
    }
}
 

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 attempt method will return true if authentication was successful. Otherwise, false will be returned.

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.


Specifying Additional Conditions

If you wish, you may also add extra conditions to the authentication query in addition to the user's e-mail and password. For example, we may verify that user is marked as "active":
 
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
   // The user is active, not suspended, and exists.
}
 

Accessing Specific Guard Instances

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.

The guard name passed to the guard method should correspond to one of the guards configured in your auth.php configuration file:
 

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

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:
 
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.
 

if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
// The user is being remembered...
}


If you are using the built-in LoginController that is shipped with Laravel, the proper logic to "remember" users is already implemented by the traits used by the controller.

If you are "remembering" users, you may use the viaRemember method to determine if the user was authenticated using the "remember me" cookie:
 

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


Authenticate A User Instance

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:
 

Auth::login($user);

// Login and "remember" the given user...
Auth::login($user, true);


You may specify the guard instance you would like to use:

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:
 

Auth::loginUsingId(1);

// Login and "remember" the given user...
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:
 

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


Example(1)

1.Open App\Http\Controller\Auth\LoginController.php and impelement as below code for authentication.

 

<?php

// Authentication mechanism
namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;

class LoginController extends Controller{
    /**
     * Handling authentication request
     *
     * @return Response
     */

    public function authenticate() {
        if (Auth::attempt(['email' => $email, 'password' => $password])) {

            // Authentication passed...
            return redirect()->intended('dashboard');
        }
    }
}

 

Related Post