3 years ago

API authentication (with passport)

Posted 3 years ago by RichardStyles

I have created a API Authentication controller, which logs in the user to the server and returns the API tokens using the "password" grant_type, that OAuth allows. As I'm testing ideas for a external App which will need to login using normal credentials, then use OAuth2 for it's API feed.

It uses two ENV which are the secrets for the Laravel passport OAuth api; API_CLIENT_ID & API_CLIENT_SECRET. from the "Laravel Password Grant Client" that passport generates (in your DB). As I do not want these to be exposed to the client side.

There was a bit of hassle getting the wrapper request to work and merge in these secrets. However it finally works, but I feel there might be a better way to call the oauth/token route.

  • Install Laravel 5.3
  • Install Auth scaffold
  • Install Laravel Passport
  • Add a new user
  • Remove Auth scaffold
  • Add ApiLoginController to web route (as POST)
Route::post('/login', '[email protected]');

The ApiLoginController extends the existing AuthenticatesUsers and the API token request is called after a successful login.

I have yet to see how login failures are handled and directed, but wanted to review the actual login methodology and if anyone can see any improvements.


namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Route;

class ApiLoginController extends Controller
    use AuthenticatesUsers;
     * The user has been authenticated.
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
    protected function authenticated(Request $request, $user)
        $email = $request->input('email');
        $password = $request->input('password');
            'username' => $email,
            'password' => $password,
            'grant_type' => 'password',
            'client_id' => env('API_CLIENT_ID'),
            'client_secret' => env('API_CLIENT_SECRET'),
            'scope' => '*'

        $tokenRequest = Request::create(
        return Route::dispatch($tokenRequest)->getContent();


Please sign in or create an account to participate in this conversation.