3

The default response of Laravel Passport comes like this:

{
    "token_type": "Bearer",
    "expires_in": 31536000,
    "access_token": djabjkdakadbakdkakjdbjkba
}

I need to add some custom response like:

{  
   "success":"true",
   "message":"Login Successful",
   "status":"200",
   "data":{
      "token_type": "Bearer",
      "expires_in": 31536000,
      "access_token":"djabjkdakadbakdkakjdbjkba"
    }
}

Can somebody help me about this idea?

Dunsin Olubobokun
  • 832
  • 10
  • 18
  • Did you search for "laravel custom responses" on the web? What about those resources does not apply to you? What have you tried? –  Oct 12 '17 at 17:03

2 Answers2

8

I have been banging my head for hours until I found the solution. This currently works for my version of Laravel 5.5.33:

  1. Add a new route in your api.php file.

    Route::post('oauth/token', 'AccessTokenController@issueToken');
    
  2. Create new file in YourProject/app/Http/Controllers/AccessTokenController.php

    <?php
    namespace App\Http\Controllers;
    
    use App\User;
    use Exception;
    use Illuminate\Database\Eloquent\ModelNotFoundException;
    use League\OAuth2\Server\Exception\OAuthServerException;
    use Psr\Http\Message\ServerRequestInterface;
    use Response;
    use \Laravel\Passport\Http\Controllers\AccessTokenController as 
    ATC;
    
    class AccessTokenController extends ATC
    {
        public function issueToken(ServerRequestInterface $request)
        {
            try {
                //get username (default is :email)
                $username = $request->getParsedBody()['username'];
    
                //get user
                //change to 'email' if you want
                $user = User::where('username', '=', $username)->first();
    
                //generate token
                $tokenResponse = parent::issueToken($request);
    
                //convert response to json string
                $content = $tokenResponse->getContent();
    
                //convert json to array
                $data = json_decode($content, true);
    
                if(isset($data["error"]))
                    throw new OAuthServerException('The user credentials were incorrect.', 6, 'invalid_credentials', 401);
    
                //add access token to user
                $user = collect($user);
                $user->put('access_token', $data['access_token']);
                //if you need to send out token_type, expires_in and refresh_token in the response body uncomment following lines
                // $user->put('token_type', $data['token_type']);
                // $user->put('expires_in', $data['expires_in']);
                // $user->put('refresh_token', $data['refresh_token']);
    
                return Response::json(array($user));
            }
            catch (ModelNotFoundException $e) { // email not found
                //return error message
                return response(["message" => "User not found"], 500);
            }
            catch (OAuthServerException $e) { //password not correct..token not granted
                //return error message
                return response(["message" => "The user credentials were incorrect.', 6, 'invalid_credentials"], 500);
            }
            catch (Exception $e) {
                ////return error message
                return response(["message" => "Internal server error"], 500);
            }
        }
    }
    
  3. Done! you can customize whatever you want over here, with whatever conditions you have. This was a lazy approach to not make your own PassportServiceProvider. Credits go to: nauvalazhar https://gist.github.com/messi89/489473c053e3ea8d9e034b0032effb1d

FrancescoMM
  • 2,845
  • 1
  • 18
  • 29
vahan terzibashian
  • 258
  • 1
  • 4
  • 9
0

There is a method called getExtraParams in BearerTokenResponse class.

    /**
     * Add custom fields to your Bearer Token response here, then override
     * AuthorizationServer::getResponseType() to pull in your version of
     * this class rather than the default.
     *
     * @param AccessTokenEntityInterface $accessToken
     *
     * @return array
     */
    protected function getExtraParams(AccessTokenEntityInterface $accessToken)
    {
        return [];
    }

By overriding it your problem will be solved.

aagjalpankaj
  • 1,160
  • 1
  • 15
  • 25