Laravel/Passport我真的需要为简单的CRUD API注册Passport :: routes()吗? [英] Laravel/Passport Do I really need to register Passport::routes() for a simple CRUD API?
问题描述
我在AuthServiceProvider的启动方法中注册了Passport::routes();
,但似乎没有使用它注册的任何路由.
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?
推荐答案
(编辑)不,如果不使用Passport::routes()
,则无需在AuthServiceProvider中注册.以下自定义控制器逻辑(改编自 https://medium.com/techcompose/create-rest-api-in-laravel-with-authentication-using-passport-133a1678a876 )仍将注册新用户并使用Passport的内置功能返回有效令牌OAuth2服务器:
(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);
}
在上面的示例中,createToken($key)
来自Passport随附的HasApiTokens
特性,无论您是否注册路线,该特性都会返回令牌. (感谢 patricus 来纠正我的最初答案.)
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.)
这篇关于Laravel/Passport我真的需要为简单的CRUD API注册Passport :: routes()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!