Skip to content

Passport Multi-Auth (Implementation) #982

Closed

Description

@billriess

Since #161 has been locked we are no longer able to discuss the issue. Before I submit a PR I want to make sure we have a common ground on what the expected behavior is for multi-provider support in Passport. More specifically, should the provider be defined at the oauth client level? This would limit that client id/secret pair to always return from a specific provider. If the gate requested another provider than what the client has defined it would return a 401.

This is the functionality I have built into my current project and I would be more than willing to issue a PR for it but I want to make sure that is what everyone is expecting.

EDIT: I should note, that if no provider is set on the oauth client then it will follow the same logic as what is in place now, so it should be backward compatible outside of the migration.

Activity

  1. changed the title [-]Passport Multi Provider[/-] [+]Passport Multi-Auth (Implementation)[/+] on Mar 5, 2019
  2. driesvints commented on Mar 5, 2019

    @driesvints
    Member

    I agree that this issue might be a good place to restart the discussion on how to implement this. I currently don't have time myself to look into this but feel free to provide thoughts here.

    Warning: I'll be removing all comments which aren't related to looking for an actual implementation to prevent this issue from de-railing like the other one. Please only discuss the possible implementation for this.

  3. billriess commented on Mar 6, 2019

    @billriess
    ContributorAuthor

    I think to get this started we should first determine if the multi-auth implementation should be enforced or not. Meaning, should the gate simply return the user against its own provider or should the client have a provider that enforces the user must come from a specific provider?

  4. pramanikriju commented on Mar 11, 2019

    @pramanikriju

    Or to make it more dynamic, the provider can be supplied in the request and the guard check can be made against that request parameter to make it compatible with as many models as required

  5. afilippov1985 commented on Mar 12, 2019

    @afilippov1985
    Contributor

    Hello everyone.
    Take a look at my proposal #987

  6. billriess commented on Mar 14, 2019

    @billriess
    ContributorAuthor

    Personally, I think each oauth_client should be limited to 1 provider but I can see how this may be limiting in some use cases. If we open it up to multiple providers per client then the developer will always be responsible for returning the correct user against any of the allowed providers.

  7. pramanikriju commented on Mar 14, 2019

    @pramanikriju

    Personally, I think each oauth_client should be limited to 1 provider but I can see how this may be limiting in some use cases. If we open it up to multiple providers per client then the developer will always be responsible for returning the correct user against any of the allowed providers.

    But isn't that the point of having multi-auth, to have the flexibility of choosing a provider but at the same time, using fallbacks for default behavior, like using the User model as is the case now.

    Personally, I too think that each oauth_client should have one provider but its better to have the implementation for multiple providers as it is might offer more functionality.

    We should probably gather more opinions on this and implement the consensus then.

  8. deleted a comment from rugiguru on Mar 18, 2019
  9. deleted a comment from billriess on Mar 18, 2019
  10. driesvints commented on Mar 18, 2019

    @driesvints
    Member

    Please remember to keep this discussion on topic.

  11. pramanikriju commented on Mar 24, 2019

    @pramanikriju

    @billriess When can we expect a PR with the functionality that you have implemented?

  12. billriess commented on Mar 24, 2019

    @billriess
    ContributorAuthor

    I was hoping for some more feedback as to what way would make the most sense for everyone. I can put a PR together later this week with my implementation and see how that goes.

  13. nikugogoi commented on Mar 28, 2019

    @nikugogoi

    I think the provider should be based on the routes... therefore different routes will have different providers.
    Suppose there is an admin model. We can set different routes in the boot() method of AuthServiceProvider like so...

    // Admin passport routes
            Passport::routes(
                null,
                [
                    'as' => 'admin.',
                    'prefix' => 'admin/oauth',
                    'middleware' => 'passport.guard:admin',
                ]
            );

    Here I am assigning a middleware(which needs to be implemented accordingly) to the the routes as to tell passport to use the admin guard which decides the provider to be used.
    What do you folks think? @billriess @driesvints

  14. zagreusinoz commented on Mar 30, 2019

    @zagreusinoz

    I think that if you're using Passport then it should be relatively safe to assume that you're not a beginner developer, and for that reason it should be as flexible as possible even if that means that a little work is required of the developer.

    I think it makes sense to have separate endpoints per your suggestion @nikugogoi for the various models so long as there is flexibility in the way those models are authenticated -- some models may not use email / password for example, we may use uuid/id and secret key or some such authentication.

    As long as the implementation allows us to attach multiple guards to a single api endpoint, e.g. if i wanted either users, or admins, or whoever to be able to access the resource.

  15. 27 remaining items

  16. driesvints commented on Apr 30, 2020

    @driesvints
    Member

    You all can thank @billriess for getting this in.

  17. lucadegasperi commented on Apr 30, 2020

    @lucadegasperi

    Thanks @billriess amazing job!

  18. hamedov93 commented on May 2, 2020

    @hamedov93

    Great work @billriess

  19. RahulDey12 commented on May 18, 2020

    @RahulDey12

    So What should I actually do then.

    Is it only supported for password grant token ?

    because provider is null for personal access token

  20. wdarins commented on May 18, 2020

    @wdarins

    Can you please also update the docs? I've created 2 guards:

            'api' => [
                'driver' => 'passport',
                'provider' => 'users',
            ],
    
            'admin' => [
                'driver' => 'passport',
                'provider' => 'admins',
            ],
    

    with the following providers:

        'providers' => [
            'users' => [
                'driver' => 'eloquent',
                'model' => App\User::class,
            ],
    
            'admins' => [
                'driver' => 'eloquent',
                'model' => App\Admin::class,
            ],
        ],
    

    now when I try to use it:

    Route::group(['middleware' => ['auth:api', 'auth:admin']], function () {
        dd(Auth::guard('admin')->check());
    });
    

    returns true even if I pass the user token. I've tried to create a new client for Admin model with the artisan command:
    php artisan passport:client --provider=admins
    but it also seems to not work as expected. It created a new client but provider field is null.

  21. driesvints commented on May 18, 2020

    @driesvints
    Member
    Route::group(['middleware' => ['auth:api,admin']], function () {
        dd(Auth::guard('admin')->check());
    });
    
  22. RahulDey12 commented on May 18, 2020

    @RahulDey12

    @driesvints is it only creates password grant token. cuz in the personal access token provider is still null

  23. billriess commented on May 18, 2020

    @billriess
    ContributorAuthor

    You set the provider when you create the oauth_client, it doesn't set the provider afterward. The purpose of this is to make sure only 1 provider can use the oauth_client. If you don't need this functionality you can leave it null. This is for password grants.

  24. RahulDey12 commented on May 18, 2020

    @RahulDey12

    @billriess is it possible to have this functionality for personal access token

  25. wdarins commented on May 18, 2020

    @wdarins

    That doesn't work for me. I'm logged in as user but Auth::guard() tells me that I'm an admin...maybe some docs on this. How can we use this to check which guard is logged in on same route handler?

  26. billriess commented on May 18, 2020

    @billriess
    ContributorAuthor

    This is for password grants not personal access tokens.

  27. wdarins commented on May 19, 2020

    @wdarins

    @billriess what's the use case for this?

  28. RahulDey12 commented on May 24, 2020

    @RahulDey12

    @billriess will it work with CreateFreshApiToken middleware

  29. donakhseputa commented on Mar 28, 2022

    @donakhseputa

    @PeterPan73 sure let me share some steps with you

    Step 1: in my config/auth.php i have following guards.

            'web' => [
                'driver' => 'session',
                'provider' => 'users',
            ],
    
            'api' => [
                'driver' => 'passport',
                'provider' => 'users',
                'hash' => false,
            ],
            'contractor' => [
                'driver' => 'passport',
                'provider' => 'contractors',
                'hash' => false,
            ],
            'crew' => [
                'driver' => 'passport',
                'provider' => 'crews',
                'hash' => false,
            ],
        ],
    

    Step 2: in my routes/api.php you can see my routes.

    Route::group(['prefix' => 'v1'], function() {
            
    	Route::post('register-user','ApiController@register_user'); //user  register
    	Route::post('user-login','ApiController@user_login');  //user login
    
           Route::post('contractor-login','ContractorController@contractor_login'); //Contractor login
           Route::post('crew-login','ContractorController@crew_login');//crew login
           Route::group(['middleware'=>'auth:api'], function() {
    	        // apis for users
    		Route::put('edit-profile','ApiController@edit_profile');
    		Route::post('create-job','ApiController@create_job');
    	});
    
    	Route::group(['middleware'=>'auth:contractor'], function() {
    	   // apis for contractors
    
    		Route::post('create-crew','ContractorController@create_crew');
    		Route::post('create-job-proposal','ContractorController@create_job_proposal');
    	});
           
    	Route::group(['middleware'=>'auth:crew'], function() {
    	    // apis for crew
    	  // Route::post('edit-profile','CrewController@edit_profile');
    	});
    });
    

    Step 3: i have updated my models file to implement HasApiTokens Trait and extends Model with Authenticatable class intead of Model

    // App\User.php
    
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Laravel\Passport\HasApiTokens;
    class User extends Authenticatable
    {
        use HasApiTokens;
    }
    
    // App\Contractor.php
    
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Laravel\Passport\HasApiTokens;
    class Contractor extends Authenticatable
    {
        use HasApiTokens;
    }
    
    // App\Crew.php
    
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Laravel\Passport\HasApiTokens;
    class User extends Authenticatable
    {
        use HasApiTokens;
    }
    

    Step 4: in my ApiController which i used for users authentication and his/her authenticated routes

    use Illuminate\Support\Str;
    use Laravel\Passport\Token;
    use Validator;
    
    class ApiController extends Controller
    {
    public function user_login(Request $request){
        	$validation = Validator::make($request->all(),[
        		'email' => 'required',
        		'password' => 'required',
        	]);
        	if($validation->fails()){
        		$data = api_validation_error('Validation Errors',$validation->messages());
        		return response()->json($data,422);
        	}
    
        	if(Auth::attempt($request->only('email','password'))){
        		$user = $request->user();
        		Token::where('user_id',$user->id)->update(['revoked'=>1]);
        		$tokenObj = $user->createToken('user access token');
        		$token = $tokenObj->token;
    			$token->expires_at = Carbon::now()->addWeeks(2);
            	$token->save();
            	$token->accessToken;
            	$token = $tokenObj->accessToken;
        		$data = Arr::add($user->toArray(),'token_detail',['access_token' => $token,'token_type' => 'Bearer']);
        		$data = api_success('Login Successfully',$data);
        		return response()->json($data);
        	}else{
        		$data = api_error('Invalid Credentials');
        		return response()->json($data);
        	}
        }
    public function edit_profile(Request $request){
           //this api will run if user pass then token
        	$validation = Validator::make($request->all(),[
        		'first_name' => 'required',
        		'last_name' => 'required',
        		'phone' => 'required',
        		'email' => 'required',
        		'address' => 'required',
        		'city' => 'required',
        		'state' => 'required',
        		'postal_code' => 'required',
        	]);
        	if($validation->fails()){
        		$data = api_validation_error('Validation Errors',$validation->messages());
        		return response()->json($data,422);
        	}
        	$user = $request->user();
        	$user->first_name = $request->first_name;
        	$user->last_name = $request->last_name;
        	$user->phone = $request->phone;
        	$user->email = $request->email;
        	$user->address = $request->address;
        	$user->city = $request->city;
        	$user->state = $request->state;
        	$user->postal_code = $request->postal_code;
        	$user->save();
        	if($user){
        		$data = api_success('Profile updated Successfully',$user);
        		return response()->json($data);
        	}
        }
    }
    

    In ContractorController.php

    class ContractorController extends Controller
    {
        //
        public function contractor_crew_login(Request $request){
        	$validation = Validator::make($request->all(),[
        		'email' => 'required',
        		'password' => 'required',
        	]);
        	if($validation->fails()){
        		$data = api_validation_error('Validation Errors',$validation->messages());
        		return response()->json($data,422);
        	}
            config(['auth.guards.contractors.driver'=>'session']); 
    
        	if(Auth::guard('contractor')->attempt($request->only('email','password'))){
        		$user = auth()->guard('contractor')->user();
        		Token::where('user_id',$user->id)->update(['revoked'=>1]);
        		$tokenObj = $user->createToken('contractor access token');
        		$token = $tokenObj->token;
    		$token->expires_at = Carbon::now()->addWeeks(2);
            	$token->save();
            	$token->accessToken;
            	$token = $tokenObj->accessToken;
        		$data = Arr::add($user->toArray(),'token_detail',['access_token' => $token,'token_type' => 'Bearer']);
        		$data = api_success('Login Successfully',$data);
        		return response()->json($data);
        	}else{
        		$data = api_error('Invalid Credentials');
        		return response()->json($data);
        	}
        }
    
        public function create_crew(Request $request){
           // this api will be accessible when contractor api pass token.
    
            $validation = Validator::make($request->all(),[
                'first_name' => 'required',
                'last_name' => 'required',
                'phone' => 'required',
                'email' => 'required',
                'password' => 'required|confirmed',
                'password_confirmation' => 'required',
                'address' => 'required',
                'city' => 'required',
                'state' => 'required',
                'services' => 'required|array',
            ]);
            if($validation->fails()){
                $data = api_validation_error('Validation Errors',$validation->messages());
                return response()->json($data,422);
            }
            if(Crew::where('email',$request->email)->exists()){
    
                $data = api_error('crew with this email already exists');
                return response()->json($data,422);
            }
            $crew = new Crew;
            $crew->crew_id = (String) Str::uuid();
            $crew->contractor_id = $request->user()->contractor_id;
            $crew->first_name = $request->first_name;
            $crew->last_name = $request->last_name;
            $crew->phone = $request->phone;
            $crew->email = $request->email;
            $crew->password = bcrypt($request->password); 
            $crew->address = $request->address;
            $crew->city = $request->city;
            $crew->state = $request->state;
            $crew->save();
                $data = api_success('Crew added successfully',$crew);
                return response()->json($data);
            }    
        }
    }
    

    for crew apis i did same as i did for contractor apis. if it authenticate the crew he will able to access that particular api.

    i hope i cleared everything and i think these code snippets are clearly understood

    how to return access_token and refresh_token??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions