Search code examples
phplaraveloauth-2.0laravel-passport

Can i auth with api with auth structure of laravel?


I want make an API for used on both front-end and admin panel with using Laravel auth structure (with make:auth) and API Authentication (with Passport) for manage all operation of actions.

My "routes/api.php" file;

Route::group(['namespace' => 'Admin', 'prefix' => 'admin', 'as' => 'api.admin.'], function () {
    Route::post('login', 'Auth\LoginController@login')->name('login');
    Route::post('logout', 'Auth\LoginController@logout')->name('logout');

    Route::group(['middleware' => 'auth:api'], function () {
        //
    });

});

My Auth\LoginController file;

<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/admin';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('admin.auth.login');
    }

    public function logout(Request $request)
    {
        auth()->logout();
        session()->flash('message', 'Some goodbye message');
        return redirect()->route('admin.login');
    }
}

When i call "/api/admin/login" url with post method and "email", "password" data, it returns following error;

RuntimeException
Session store not set on request.

I think solved above error with following method in $middlewareGroup in Kernel.php api group; My app/Http/Kernel.php file;

\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class

Session store not set on request. error is solved but, it returns MethodNotAllowedHttpException now.

I can solved these problems with other method but i want use auth standart of Laravel.

Is this possible?

Thank you all.


Solution

  • It is possible although it's a bit more involved than just switching the login url. You're going for the Password Grant Flow so user's can authenticate with their existing email and password credentials.

    You do not need to enable the session for this to work. The basic run down is you post your email and password to a route which proxies the request to the OAuth2 server. You'll relay the authentication and refresh tokens back to the user, who's responsibility it is then to attach the access token to each subsequent request using the Authorization: Bearer LongEncryptedTokenHere... header.

    To make things easier, Laravel offers the CreateFreshApiTokens middleware which will automatically authorize and refresh the token each request. You can read about Consuming Your API With JavaScript here.

    An example of requesting a token using the password grant and Guzzle:

    $http = new GuzzleHttp\Client;
    
    $response = $http->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'password',
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
            'username' => 'taylor@laravel.com',
            'password' => 'my-password',
            'scope' => '',
        ],
    ]);
    
    return json_decode((string) $response->getBody(), true);
    

    From Password Grant Tokens