Laravel/Passport Do I really need to register Passport::routes() for a simple CRUD API?

一笑奈何 提交于 2020-01-15 10:26:49

问题


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?


回答1:


(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.)



来源:https://stackoverflow.com/questions/57435991/laravel-passport-do-i-really-need-to-register-passportroutes-for-a-simple-cr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!