1

I registered Passport::routes(); in the boot method of AuthServiceProvider, but I don't seem to be using any of the routes it registers.

Do I need them? What are they used for? Can't I just use my custom routes that map to a custom controller for login, register and logout methods?

Erich
  • 2,408
  • 18
  • 40
soufiane yakoubi
  • 861
  • 11
  • 31
  • if you going to use Passport as an 0Auth server absolutely. If you are not going to then no, but keep in mind you will need some type of authentication. – Brad Goldsmith Aug 09 '19 at 20:30

1 Answers1

2

(EDITED) No, you do not need to register Passport::routes() in AuthServiceProvider if you don't use them. The following custom controller logic (adapted from https://medium.com/techcompose/create-rest-api-in-laravel-with-authentication-using-passport-133a1678a876) will still register a new user and return a valid token using Passport's built-in OAuth2 server:

public function register(Request $request)
{
    $validator = Validator::make($request->all(), [ 
        'name' => 'required', 
        'email' => 'required|email', 
        'password' => 'required', 
        'retype_password' => 'required|same:password', 
    ]);

    if ($validator->fails()) { 
        return response()->json($validator->errors(), Response::HTTP_FORBIDDEN);            
    }

    $user = User::firstOrCreate(
        ['email' => $request->email],
        ['name' => $request->name, 'password' => bcrypt($request->password)]
    ); 

    $response = [
        'token' => $user->createToken('MyApp')->accessToken
    ];

    return response()->json($response, Response::HTTP_CREATED);
}

In the example above, createToken($key) comes from the HasApiTokens trait included with Passport which will return the token, regardless of whether you register the routes. (Thanks to patricus for correcting my initial answer.)

Erich
  • 2,408
  • 18
  • 40
  • 1
    The `createToken()` method interacts with the OAuth server to create a personal access token, but it doesn't do it through the routes. The `Passport::routes()` are not needed for the code you have posted. – patricus Aug 10 '19 at 00:02
  • @patricus you're right, thanks! my api routes using this controller logic still work after commenting out the route registration. updating my answer – Erich Aug 10 '19 at 19:21