DEV Community

User Authentication using Laravel's passport

Sathish on March 19, 2018

First, let's answer the basic question - What is User Authentication? User authentication is a process that allows an application to ver...
Collapse
 
kabircse profile image
Kabir Hossain

I am trying to implement laravel passport on laravel 6. But I am getting an error.
Login and registration are ok. But I am getting an error when trying to fetch(authentic) pages.

The error is here pastebin.com/1M4iC3u5

My api.php



Route::group(['prefix'=>'v1'],function(){
        Route::post('register', 'API\Auth\RegisterController@register');
        Route::post('login', 'API\Auth\RegisterController@login');
        Route::get('gas_stations', 'API\GasStationController@index');
        //it works
        //Route::get('brands', 'API\BrandController@index');


        Route::group(['middleware'=>['auth:api']],function() {
            //it is not working
            Route::get('brands', 'API\BrandController@index');
        });    
    });
Collapse
 
malwarebo profile image
Irfan

I don't know how you have set up the flow but here is something that should probably work.

Inside the BrandController add this to the constructor.

$this->middleware(['auth'']);

Next, the index function inside the controller should look like this:

public function index()
    {
        $brands = Brands::all();
        return view('brands.index');
    }

Then use the Route directly as:

Route:get(/brands, BrandController@index);
Collapse
 
kabircse profile image
Kabir Hossain

Thanks a lot

Collapse
 
olivedev profile image
olivedev

Laravel Passport is definitely the best option for api token authentication in Laravel based apps. It automatically generates api token in Laravel apps. This make it easy to configure and efficient to use in your apps.

Collapse
 
sathish profile image
Sathish

That's why I wrote the tutorial. 😉

Collapse
 
hariwac profile image
Harinarayanan T

Hi,

Suppose I want to validate this condition while login a user using API

$aCredential = ['username' => $userName, 'password' => $password, 'user_type' => 1, 'status' => 1];

in this case do we need to separately validate each data rather than

if(Auth::attemp(aCredential))

In laravel 5.5, if you use passport attempt() will trigger error - function does not exits. So what will be the solution?

Collapse
 
jacobhenning profile image
Jacob Henning

Awesome article! I found it super helpful.

I did have a question for you though. In your logout function, you go through the following steps:

1) Get token from the header
2) Parse token to get the id
3) Retrieve token from user tokens using said id
4) Take this retrieved token, and revoke it.

I wrote my logout function differently as follows

$request->user()->token()->revoke();

1) Grab the user from the request
2) Grab the current toke from user
3) Revoke the token taken from the user

I chose not to use the id at all. My question is should I be using the id? Is there ever a time where the token I'm logging out is not going to be the token assigned to the current user?

Collapse
 
lexiebkm profile image
Alexander B.K.

Your authentication controller looks more readable/clearer than others I find in other articles. But maybe because I don't have prior knowledge of OAuth. Therefore I should first read the fundamental concepts explained in oauth2.thephpleague.com/ and even in tools.ietf.org/html/rfc6749, before I can proceed to code using Laravel Passport. Now, I know why Laravel documentation suggest that I should get familiar with OAuth before continuing. :)
Without good knowledge in OAuth, I feel I will only be able to copy paste code from others.

Collapse
 
lexiebkm profile image
Alexander B.K.

I can see you use Password Grant in this example from your AuthenticationController. But when I compare with what I read in Laravel documentation : laravel.com/docs/7.x/passport#requ..., I wonder how you get to use your code for issuing access token with Password Grant flow.
I know the User model uses HasApiTokens trait that has createToken method. But there is no clue, either in that HasApiTokens trait or in your code which specifies sufficient parameters usually required for Password Grant, i.e client_id and client_secret.
Maybe I missed something, but where in your code those parameters for Password grant are supplied for requesting access token ?

As as comparison, this is code snippet I find in other article :

public function login(Request $request) {
    $input = $this->validate($request, [
        'email' => 'required|email|exists:users,email',
        'password' => 'required|min:6',
    ], [
        'email.exists' => 'The user credentials were incorrect.',
    ]);

    request()->request->add([
        'grant_type' => 'password',
        'client_id' => env('PASSWORD_CLIENT_ID'),
        'client_secret' => env('PASSWORD_CLIENT_SECRET'),
        'username' => $input['email'],
        'password' => $input['password'],
    ]);

    $response = Route::dispatch(Request::create('/oauth/token', 'POST'));
    $data = json_decode($response->getContent(), true);
    if (!$response->isOk()) {
        return response()->json($data, 401);
    }
    return $data;
}

We see it also includes /oauth/token route for requesting access token as always mentioned in Laravel documentation.

Collapse
 
chrismuga profile image
ChrisMuga

Thank you, This helped me so much!

Collapse
 
sathish profile image
Sathish

Happy about that.

Collapse
 
pixelspy profile image
pixelSpy

hey thks for your great tutorial!
how do you then link this to your front end in vue.js for example?
i'm quite new to APIs
cheers

Collapse
 
sathish profile image
Sathish

No linking required. Call the appropriate API calls.

Collapse
 
webfacer profile image
Ilic Davor

if someone has issue to velidate password, try this:
try replacing the if statment with password by
'if(Hash::check($request->password, $user->password)) {//...}'

Collapse
 
hari03 profile image
Hariharan

How would you approach if you have the get the user details from a lumen endpoint?

Collapse
 
fawad0301 profile image
Fawad Ali

Nice and clean guide I like it...

Collapse
 
tripathi661 profile image
deepti

Hi,

How We can use the same API for login, Register through the web page?
I want to use the same API for web and REST both.