T.B
T.B

Reputation: 11

How to use both web and api with two kind of users in Laravel?

I am doing a RESTful API (for a mobile app) and a web interface using the blade engine. I have two kinds of users, one is a "gestionnaire" (for the web interface) and the other one is a "client" (for the mobile app).

Right now I can authenticate the user "gestionnaire" using the php artisan make:auth command, but I cannot authenticate the client even though I modified the auth.php as follows:

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'clients',
    ],


    'guards' => [

        'api' => [
            'driver' => 'passport',
            'provider' => 'clients',
            'hash' => false,
        ],

        'web' => [
            'driver' => 'session',
            'provider' => 'gestionnaires',
        ],

    ],


    'providers' => [
        'clients' => [
            'driver' => 'eloquent',
            'model' => App\Client::class,
        ],
        'gestionnaires' => [
            'driver' => 'eloquent',
            'model' => App\Gestionnaire::class,
        ],

    ],

    'passwords' => [
        'clients' => [
            'provider' => 'clients',
            'table' => 'password_resets',
            'expire' => 60,
        ],

    ],

At the moment my controllers look like this :


class LoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = '/home';

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

And this :


class AuthController extends Controller
{
    public function login(Request $request) {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
            //'remember_me' => 'boolean'
        ]);
        $credentials = request(['email', 'password']);
        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        $user = $request->user();
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;
        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);
        $token->save();
        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);
    }

    public function user(Request $request)
    {
        return response()->json($request->user());
    }
}

My routes in web.php are looking like this :


Route::get('/', function () { return view('welcome'); });

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

And in api.php

Route::group([
    'prefix' => 'auth'
], function () {
    Route::post('login', 'Auth\AuthController@login')->name('login');
    Route::post('register', 'Auth\AuthController@register');
    Route::group([
        'middleware' => 'auth:api'
    ], function() {
        Route::get('logout', 'Auth\AuthController@logout');
        Route::get('user', 'Auth\AuthController@user');
    });
});

With this code

I am able to connect through the web interface but not through the API. I am using Postman to process request but I am receiving the following message : Unauthorized when I am trying to sign in.

I already checked the body of my request (the email and password) and it is correct.

Does anybody have an idea on what I should do ?

Upvotes: 1

Views: 1034

Answers (1)

pdchaudhary
pdchaudhary

Reputation: 388

You can use Auth::shouldUse('api'); in api.

OR

You can create middleware for that

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth; 
use App\User; 

class ConditionalApisHandler 
{


    public function handle($request, Closure $next)
    {
        Auth::shouldUse('api');   
        return $next($request);
    }
}

In api.php

Route::group(['middleware' => 'conditionalApisHandler'], function(){
    Route::post('example','API\ExampleController@example');

});

Upvotes: 1

Related Questions