Registering User with Laravel Passport

20,083

Solution 1

In your API create route as

Route::post('register','Api\UsersController@create');

And in UsersController create method create()

function create(Request $request)
{
    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $request
     * @return \Illuminate\Contracts\Validation\Validator
     */
    $valid = validator($request->only('email', 'name', 'password','mobile'), [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6',
        'mobile' => 'required',
    ]);

    if ($valid->fails()) {
        $jsonError=response()->json($valid->errors()->all(), 400);
        return \Response::json($jsonError);
    }

    $data = request()->only('email','name','password','mobile');

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'mobile' => $data['mobile']
    ]);

    // And created user until here.

    $client = Client::where('password_client', 1)->first();

    // Is this $request the same request? I mean Request $request? Then wouldn't it mess the other $request stuff? Also how did you pass it on the $request in $proxy? Wouldn't Request::create() just create a new thing?

    $request->request->add([
        'grant_type'    => 'password',
        'client_id'     => $client->id,
        'client_secret' => $client->secret,
        'username'      => $data['email'],
        'password'      => $data['password'],
        'scope'         => null,
    ]);

    // Fire off the internal request. 
    $token = Request::create(
        'oauth/token',
        'POST'
    );
    return \Route::dispatch($token);
}

And after creating new user, return access token.

Solution 2

And after I year, I figured out how to implement the full cycle.

@Nileshsinh method shows the register cycle.

And here is login & refresh token parts:

Route::post('auth/token', 'Api\AuthController@authenticate');
Route::post('auth/refresh', 'Api\AuthController@refreshToken');

Methods:

class AuthController extends Controller
{
    private $client;

    /**
     * DefaultController constructor.
     */
    public function __construct()
    {
        $this->client = DB::table('oauth_clients')->where('id', 1)->first();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    protected function authenticate(Request $request)
    {
        $request->request->add([
            'grant_type' => 'password',
            'username' => $request->email,
            'password' => $request->password,
            'client_id' => $this->client->id,
            'client_secret' => $this->client->secret,
            'scope' => ''
        ]);

        $proxy = Request::create(
            'oauth/token',
            'POST'
        );

        return \Route::dispatch($proxy);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    protected function refreshToken(Request $request)
    {
        $request->request->add([
            'grant_type' => 'refresh_token',
            'refresh_token' => $request->refresh_token,
            'client_id' => $this->client->id,
            'client_secret' => $this->client->secret,
            'scope' => ''
        ]);

        $proxy = Request::create(
            'oauth/token',
            'POST'
        );

        return \Route::dispatch($proxy);
    }
}

Solution 3

Reading this while Laravel 6 has recently been deployed, my solution for this is as following.

When you've followed the steps defined in Laravel's passport documentation and you added the HasApiTokens trait to the User model, you can call a createToken function on your user entities.

Also, in your RegisterController there's a registered function from the RegistersUsers trait that you can implement which is called when a user is successfully registered. So you could implement this as following:

protected function registered(Request $request, User $user)
{
    $token = $user->createToken('tokenName');

    return response()->json([
        'user' => $user,
        'token' => $token->accessToken,
    ]);
}

See the register function in the RegistersUsers trait for more information about the registration cycle..

Share:
20,083

Related videos on Youtube

senty
Author by

senty

Harder, Better, Faster, Stronger...

Updated on October 01, 2020

Comments

  • senty
    senty over 3 years

    I set up password grant (it's backend for an app). Now, I can send a post request to oauth/token and it works on Postman. However, what if I want to register user from the api too?

    I understand I can use current /register route, however, then will I need to redirect the user back to the login page and he logs in again with his credentials?

    Or in the RegisterController, in registered() function, should I do I redirect to the oauth/token route? (For this, please note that I am sending, all the 5 data in 'x-www-form-urlencoded' and it seems to work. However, do I need to separate some in headers? It's blurry for me, so just wanted to ask when I have the chance).

    Or should I add something in the oauth/token method like this guy? Actually, I tried to catch the posted $request data on AccessTokenController@issueTokenmethod inside library, however I couldn't figure out how to manipulate the parsedBody array. If I trigger my register function from the actual library, how would I know if it's register or login?

    Maybe I am missing out some information, but I couldn't find anything based on this topic. What is the proper way of handling registering user in Passport?


    Update: Accepted answer shows the 'register' cycle; and below it I have added 'login' and 'refresh token' implementations. Hope it helps :)

  • mafortis
    mafortis over 5 years
    Hi i have 2 questions: 1 why do you get static user id in __construct part? 2 why should we refresh the token?(i mean the benefit is what?)
  • senty
    senty over 5 years
    @mafortis - 1 - It is the oauth_client id for your app. Think it as you use any 3rd party api. When you sign up, you first sign up your application for API Key, API secret, right? (Think FaceBook api for example, you get credentials for your application). It's same here. OAuth Client is that. However, as I didn't want to open my api to public, I didn't have a lot of oauth clients, so I just fetch it. Otherwise, (if I was going to have many oauth clients), then I'd accept the App's OAuth credentials (api key & api secret), together as user credentials.
  • senty
    senty over 5 years
    2 - refresh token is just for security, because as token is the 'authentication' of any user, if someone else has his token, he can impersonate that user :) That's why it's good to refresh token :) (Big companies expire tokens in 10~ mins afaik) - Hope this helps :)
  • andcl
    andcl about 5 years
    Well explained and worth giving a try: voerro.com/en/tutorials/r/…
  • Manish
    Manish over 4 years
    but this seems to generate a personal token not access token or refresh token.
  • Samuel Bié
    Samuel Bié almost 4 years
    This answers surelly works. but it does not check witch client app is making the request
  • Mladen Janjetovic
    Mladen Janjetovic over 3 years
    This is not password grant as asked in the question