使用 laravel 护照从 api 路由注册新用户
Posted
技术标签:
【中文标题】使用 laravel 护照从 api 路由注册新用户【英文标题】:register new user from api route using laravel passport 【发布时间】:2017-05-27 11:31:20 【问题描述】:我已经安装了 laravel 5.3 和 passport 包。
我一步一步地按照文档
我可以使用以下路由POST /oauth/token
和以下参数
-
用户名
密码
client_secret
grant_type
client_id
我得到以下响应
"token_type": "Bearer",
"expires_in": 31536000,
"access_token": "access token here",
"refresh_token": "refresh token here"
然后我请求GET /api/user
带有以下标题
-
Authorization = "此处的不记名访问令牌"
接受 = 应用程序/json(可选)
这很好用,所以所有的 api。
我遇到的问题是我在第一个请求中验证并输入了他的用户名和密码并将访问令牌返回给我的用户是我从 laravel web view /register 创建的用户
如何从api路由文件创建新用户或注册新用户
点赞POST /api/register
用户第一次注册后需要进行身份验证。
我应该在没有 oauth 的情况下创建这条路线来注册,然后如果注册成功,他会请求 POST /oauth/token
进行身份验证还是什么?
我错过了什么吗??
更新
clent_secret
在所有用户请求中保持不变是否正确,或者每个用户应该有不同的 clent_secret,如果它需要对用户进行身份验证,如何创建 aclent 秘密?
【问题讨论】:
您可以通过将用户添加到用户表来注册用户...无需对护照做任何事情,然后当您想检索访问令牌时调用登录功能,关于 client_secret 我个人为所有用户使用一个,创建它php artisan passport:install
【参考方案1】:
如果我正确理解您的问题,您想注册新用户并在注册后从/oauth/token
获得令牌。为此,您可以使用代理。我使用了类似的东西,我按照以下步骤操作。这适用于登录和注册
注册用户并通过您的注册方法向/oauth/token
端点发送HTTP请求
public function register(RegisterRequest $request)
$user = User::create($request->all());
$response = $this->authenticationProxy->attemptLogin($request->email, $request->password);
return response()->json(compact('response', 'user'), 201);
然后在您的proxy
类中,调用/oauth/token
public function attemptLogin($email, $password)
$http = new GuzzleHttp\Client;
$response = $http->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => env('CLIENT_ID'),
'client_secret' => env('CLIENT_SECRET'),
'username' => $email,
'password' => $password,
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
希望这会有所帮助。您也可以使用类似的方法登录。
【讨论】:
【参考方案2】:最快的方法是在你的 verifyCsrfToken.php 类中添加一个异常
protected $except = [
'register'
];
然后您可以发布到您的注册模型,然后使用 oauth/token 访问此帐户。
【讨论】:
以上是关于使用 laravel 护照从 api 路由注册新用户的主要内容,如果未能解决你的问题,请参考以下文章