使用 Laravel Passport 注册用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44172818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:02:33  来源:igfitidea点击:

Registering User with Laravel Passport

phplaraveloauthlaravel-5.4laravel-passport

提问by senty

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

我设置了密码授予(它是应用程序的后端)。现在,我可以向oauth/tokenPostman发送 post 请求,它可以在 Postman 上运行。但是,如果我也想从 api 注册用户怎么办?

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

我知道我可以使用当前/register路由,但是,我是否需要将用户重定向回登录页面并让他使用他的凭据再次登录?

Or in the RegisterController, in registered()function, should I do I redirect to the oauth/tokenroute? (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).

或者在 RegisterController 中,在registered()功能上,我应该重定向到oauth/token路由吗?(为此,请注意我正在发送 'x-www-form-urlencoded' 中的所有 5 个数据,它似乎有效。但是,我需要在标题中分离一些数据吗?对我来说很模糊,所以只是想要问我什么时候有机会)。

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

或者我应该oauth/token这个人一样在方法中添加一些东西?实际上,我试图在库中的方法$request上捕获发布的数据AccessTokenController@issueToken,但是我不知道如何操作parsedBody数组。如果我从实际库中触发我的注册功能,我怎么知道它是注册还是登录?

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?

也许我遗漏了一些信息,但我找不到基于此主题的任何信息。在 Passport 中处理注册用户的正确方法是什么?



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

更新:接受的答案显示“注册”周期;在它下面我添加了“登录”和“刷新令牌”实现。希望能帮助到你 :)

采纳答案by Nileshsinh Rathod

In your API create route as

在您的 API 中,将路由创建为

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

And in UsersController create method create()

并在 UsersController 中创建方法 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.

创建新用户后,返回访问令牌。

回答by senty

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

一年之后,我想出了如何实施完整的周期。

@Nileshsinh method shows the register cycle.

@Nileshsinh 方法显示了寄存器周期。

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);
    }
}

回答by Alserda

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

在最近部署 Laravel 6 时阅读本文,我的解决方案如下。

When you've followed the steps defined in Laravel's passport documentationand you added the HasApiTokenstrait to the Usermodel, you can call a createTokenfunction on your user entities.

当您按照 Laravel 的通行证文档中定义的步骤并将HasApiTokens特征添加到User模型时,您可以createToken在您的用户实体上调用一个函数。

Also, in your RegisterControllerthere's a registeredfunction from the RegistersUserstrait that you can implement which is called when a user is successfully registered. So you could implement this as following:

此外,在您的trait 中,您可以实现RegisterController一个registered函数,该函数RegistersUsers在用户成功注册时被调用。所以你可以按如下方式实现:

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

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

See the registerfunction in the RegistersUserstrait for more information about the registration cycle..

有关注册周期的更多信息,请参阅特征中的register函数RegistersUsers