php Laravel 的 5.3 通行证和 API 路由
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39525968/
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
Laravel's 5.3 passport and api routes
提问by Andrei
I'm using Laravel Framework version 5.3.9, fresh download nothing added on via composer(except "laravel/passport": "^1.0"
).
我正在使用 Laravel Framework 5.3.9 版,全新下载没有通过作曲家添加任何内容(除了"laravel/passport": "^1.0"
)。
I did all the things suggested in the docs. Tables are created, routes are up, everything works fine. However I need passport for an API.
我做了文档中建议的所有事情。表已创建,路由已启动,一切正常。但是我需要 API 的护照。
My routes look like so:
我的路线如下所示:
+--------+----------+-----------------------------------------+----------------------+----------------------------------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+-----------------------------------------+----------------------+----------------------------------------------------------------------------+------------+
| | GET|HEAD | / | | Closure | web |
| | GET|HEAD | api/v1/users/register | api::users::register | App\Http\Controllers\Api\V1\SocialController@register | api,auth |
| | POST | oauth/authorize | | \Laravel\Passport\Http\Controllers\ApproveAuthorizationController@approve | web,auth |
| | GET|HEAD | oauth/authorize | | \Laravel\Passport\Http\Controllers\AuthorizationController@authorize | web,auth |
| | DELETE | oauth/authorize | | \Laravel\Passport\Http\Controllers\DenyAuthorizationController@deny | web,auth |
| | GET|HEAD | oauth/clients | | \Laravel\Passport\Http\Controllers\ClientController@forUser | web,auth |
| | POST | oauth/clients | | \Laravel\Passport\Http\Controllers\ClientController@store | web,auth |
| | PUT | oauth/clients/{client_id} | | \Laravel\Passport\Http\Controllers\ClientController@update | web,auth |
| | DELETE | oauth/clients/{client_id} | | \Laravel\Passport\Http\Controllers\ClientController@destroy | web,auth |
| | GET|HEAD | oauth/personal-access-tokens | | \Laravel\Passport\Http\Controllers\PersonalAccessTokenController@forUser | web,auth |
| | POST | oauth/personal-access-tokens | | \Laravel\Passport\Http\Controllers\PersonalAccessTokenController@store | web,auth |
| | DELETE | oauth/personal-access-tokens/{token_id} | | \Laravel\Passport\Http\Controllers\PersonalAccessTokenController@destroy | web,auth |
| | GET|HEAD | oauth/scopes | | \Laravel\Passport\Http\Controllers\ScopeController@all | web,auth |
| | POST | oauth/token | | \Laravel\Passport\Http\Controllers\AccessTokenController@issueToken | |
| | POST | oauth/token/refresh | | \Laravel\Passport\Http\Controllers\TransientTokenController@refresh | web,auth |
| | GET|HEAD | oauth/tokens | | \Laravel\Passport\Http\Controllers\AuthorizedAccessTokenController@forUser | web,auth |
| | DELETE | oauth/tokens/{token_id} | | \Laravel\Passport\Http\Controllers\AuthorizedAccessTokenController@destroy | web,auth |
+--------+----------+-----------------------------------------+----------------------+----------------------------------------------------------------------------+------------+
All the web
routes are there, there are no api
related routes, since Passport doesn't provide anything of that sort out of the box.
所有的web
路线都在那里,没有api
相关的路线,因为 Passport 没有提供任何开箱即用的东西。
The API itself is intended to be used by a trusted client, it's made for a mobile application that does require a login however, said login will bypass a few steps.
API 本身旨在供受信任的客户端使用,它是为确实需要登录的移动应用程序而设计的,但是,所述登录将绕过几个步骤。
Once a user access the /register
route, the registration process itself is quite simple: access the user's facebook account an grab a few fields - email, facebook id, name an profile picture and from that point onwards the users is considered registered. But the user will NOTlogin with facebook(this is a very important aspect). The consumer app will be issued a token and use that token to access various endpoints of the api(that require a token to use).
一旦用户访问该/register
路线,注册过程本身就非常简单:访问用户的 facebook 帐户并获取一些字段 - 电子邮件、facebook id、命名个人资料图片,从那时起用户就被视为已注册。但是用户不会使用 facebook 登录(这是一个非常重要的方面)。消费者应用程序将获得一个令牌并使用该令牌访问 api 的各种端点(需要令牌才能使用)。
So it boils down to this. I need to issue an access token to the consumer app that access the API. The API itself will only have one client, that is the mobile app itself. Users that use the app are not considered clients of the API but clients of the mobile app itself.
所以归结为这个。我需要向访问 API 的消费者应用程序发出访问令牌。API 本身只有一个客户端,即移动应用程序本身。使用该应用程序的用户不被视为 API 的客户端,而是移动应用程序本身的客户端。
So far Passport is a headache to work with when it comes to implementing API related stuff, either that or I can't figure out how to make it work properly.
到目前为止,在实现 API 相关的东西时,Passport 是一个令人头疼的问题,或者我无法弄清楚如何让它正常工作。
I've created a test client in the oauth_clients
table that looks like so:
我在oauth_clients
表中创建了一个测试客户端,如下所示:
I'm using Postman to access api/v1/users/register
route that has the auth
middleware with the following JSON application/json
我正在使用 Postman 访问api/v1/users/register
具有以下auth
中间件的路由JSON application/json
{
"grant_type" : "authorization_code",
"client_id" : 5,
"client_secet": "y5dvPIOxQJOjYn7w2zzg4c6TRrphsrNFWbG4gAUL"
}
Which of course will result in a
这当然会导致
{"error":"Unauthenticated."}
It makes perfect sense.
Out of pure curiosity I changed the /register
route to this:
这是完全有道理的。出于纯粹的好奇,我改变了/register
路线:
Route::group([
'middleware' => [
],
], function ()
{
Route::group([
'prefix' => 'users',
'as' => 'users::',
], function ()
{
// Route::get('/register', ['as' => 'register', 'uses' => 'Api\V1\SocialController@register',]);
Route::post('/register', ['as' => 'register', 'uses' => '\Laravel\Passport\Http\Controllers\AccessTokenController@issueToken',]);
});
});
With the same json
as before. That resulted in {"error":"invalid_client","message":"Client authentication failed"}
.
跟json
以前一样。这导致{"error":"invalid_client","message":"Client authentication failed"}
.
I've tracked down the function that, I think, handles the validateClient
part in vendor/league
oauth2-server/src/Grant/AbstractGrant`.
我已经找到了处理oauth2-server/src/Grant/AbstractGrant` 中的validateClient
部分的函数。vendor/league
The $client
is null. Now this may or may not be related to Passport, since the documentation on it rather lacking and the thought of digging thru a monster of a package to track down the error that may be largely due to me not doing something right doesn't strike me as a good idea, I'm out of options. To be perfectly honest I don't even know what the problem is.
该$client
为空。现在这可能与 Passport 相关,也可能不相关,因为关于它的文档相当缺乏,并且通过一个包的怪物来追踪可能主要是由于我没有做正确的事情的错误的想法并没有让我感到震惊作为一个好主意,我别无选择。老实说,我什至不知道问题是什么。
Really, at this point any sort pointing in the right direction is more than welcome.
真的,在这一点上,任何指向正确方向的方式都非常受欢迎。
The part in questions is
问题的部分是
回答by Shuja Ahmed
The problem with Laravel 5.3 passport is that unlike previous OAuth 2.0 Server for Laravel library offered by lucadegasperi, it has no API to make clients directly. So as if now the client can only be made through the front-end. FYI we wanted to use laravel passport solely for our mobile app so while creating and registering user we would have only EMAIL & Password and in some cases only Facebook UserID for facebook sign-in. So the following approach worked pretty well for our case and might differ for your scenario but may help you in the longer term to play around with laravel passport.
Laravel 5.3 护照的问题在于,与之前由 lucadegasperi 提供的 Laravel 库的 OAuth 2.0 服务器不同,它没有 API 可以直接创建客户端。所以好像现在客户端只能通过前端制作。仅供参考,我们想仅将 laravel 护照用于我们的移动应用程序,因此在创建和注册用户时,我们只有电子邮件和密码,在某些情况下,只有 Facebook 用户 ID 用于 Facebook 登录。因此,以下方法对我们的案例非常有效,并且可能因您的情况而异,但从长远来看可能会帮助您使用 laravel 护照。
Note: Before following the below its assumed you have enabled Password Grant in your application.
注意:在执行以下操作之前,假设您已在应用程序中启用密码授予。
So the way we solved it for our project on laravel 5.3 is as follows:
所以我们在laravel 5.3上的项目中解决的方法如下:
in the oauth_clients convert the id field into a normal field i.e. remove it as being primary key and make the data type as varchar so that we can store email address as client_ids as they are also unique for your system. Incase of Facebook login we store Facebook user IDs here in this column which again will be unique for each our client. Also for other tables like: oauth_access_tokens, oauth_auth_codes & oauth_personal_access_clients change client_id to VARCHAR(255) so that it can store email addresses or Facebook User IDs.
Now go to your models and create a model for oauth_clients table so that you can create client programmatically from the code while creating users.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class OauthClient extends Model { protected $table = 'oauth_clients'; }
Then in your api.php route file add the following route:
Route::post('/register-user', function (Request $request) { $name = $request->input('name'); $email = $request->input('email'), $password = $request->input('password'), // save new user $user = \App\User::create([ 'name' => $name, 'email' => $email, 'password' => bcrypt($password), ]); // create oauth client $oauth_client = \App\OauthClient::create([ 'user_id' => $user->id, 'id' => $email, 'name' => $name, 'secret' => base64_encode(hash_hmac('sha256',$password, 'secret', true)), 'password_client' => 1, 'personal_access_client' => 0, 'redirect' => '', 'revoked' => 0, ]); return [ 'message' => 'user successfully created.' ]; });
在 oauth_clients 中,将 id 字段转换为普通字段,即将其作为主键删除,并将数据类型设为 varchar,以便我们可以将电子邮件地址存储为 client_ids,因为它们对于您的系统也是唯一的。在 Facebook 登录的情况下,我们将 Facebook 用户 ID 存储在此列中,这对于我们的每个客户来说也是唯一的。同样对于其他表,例如:oauth_access_tokens、oauth_auth_codes 和 oauth_personal_access_clients 将 client_id 更改为 VARCHAR(255),以便它可以存储电子邮件地址或 Facebook 用户 ID。
现在转到您的模型并为 oauth_clients 表创建一个模型,以便您可以在创建用户时通过代码以编程方式创建客户端。
<?php namespace App; use Illuminate\Database\Eloquent\Model; class OauthClient extends Model { protected $table = 'oauth_clients'; }
然后在你的 api.php 路由文件中添加以下路由:
Route::post('/register-user', function (Request $request) { $name = $request->input('name'); $email = $request->input('email'), $password = $request->input('password'), // save new user $user = \App\User::create([ 'name' => $name, 'email' => $email, 'password' => bcrypt($password), ]); // create oauth client $oauth_client = \App\OauthClient::create([ 'user_id' => $user->id, 'id' => $email, 'name' => $name, 'secret' => base64_encode(hash_hmac('sha256',$password, 'secret', true)), 'password_client' => 1, 'personal_access_client' => 0, 'redirect' => '', 'revoked' => 0, ]); return [ 'message' => 'user successfully created.' ]; });
In the above code snippet, you have to note that to generate the oauth_client secret you have to use some strong formula of encryption that you feel comfortable using it with your application. Also, use the same technique to generate the secret key on your mobile app for the respective client/user.
在上面的代码片段中,您必须注意,要生成 oauth_client 机密,您必须使用一些您觉得在您的应用程序中使用它的强大加密公式。此外,使用相同的技术在您的移动应用程序上为相应的客户端/用户生成密钥。
Now you can use the standard POST API offered by laravel passport to request access token through password grant using "oauth/token" using the following parameters:
grant_type : 'password' client_id : '<email with which the user is registered>' client_secret : '<generate the client secret from the mobile app>' username : '<email with which the user is registered>' password : '<password entered by the user>' scope : '<leave empty as default>'
The above will give you a response, if everything is correct, similar to :
{ "token_type": "Bearer", "expires_in": 3155673600, "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjMwZmM0MDk1NWY5YjUwNDViOTUzNDlmZjc2M2ExNDUxOTAxZjc5YTA5YjE4OWM1MjEzOTJlZmNiMDgwOWQzMzQwM2ExZWI4ZmMyODQ1MTE3In0.eyJhdWQiOiJzaHVqYWhtQGdtYWlsLmNvbSIsImp0aSI6IjMwZmM0MDk1NWY5YjUwNDViOTUzNDlmZjc2M2ExNDUxOTAxZjc5YTA5YjE4OWM1MjEzOTJlZmNiMDgwOWQzMzQwM2ExZWI4ZmMyODQ1MTE3IiwiaWF0IjoxNDc4MTQ1NjMyLCJuYmYiOjE0NzgxNDU2MzIsImV4cCI6NDYzMzgxOTIzMiwic3ViIjoiMSIsInNjb3BlcyI6W119.dj3g9b2AdPCK-im5uab-01SP71S7AR96R0FQTKKoaZV7M5ID1pSXDlmZw96o5Bd_Xsy0nUqFsPNRQsLvYaOuHZsP8v9mOVirBXLIBvPcBc6lDRdNXvRidNqeh4JHhJu9a5VzNlJPm3joBYSco4wYzNHs2BPSxXuuD3o63nKRHhuUHB-HwjVxj2GDwzEYXdZmf2ZXOGRJ99DlWGDvWx8xQgMQtd1E9Xk_Rs6Iu8tycjBpKBaC24AKxMI6T8DpelnFmUbMcz-pRsgCWCF_hxv6FpXav3jr1CLhhT58_udBvXjQAXEbtHeB7W_oaMcaqezHdAeOWDcnqREZHsnXHtKt0JpymcTWBkS2cg7sJzy6P9mOGgQ8B4gb8wt44_kHTeWnokk4yPFRZojkHLVZb8YL6hZxLlzgV1jCHUxXoHNe1VKlHArdlV8LAts9pqARZkyBRfwQ8oiTL-2m16FQ_qGg-9vI0Suv7d6_W126afI3LxqDBi8AyqpQzZX1FWmuJLV0QiNM0nzTyokzz7w1ilJP2PxIeUzMRlVaJyA395zq2HjbFEenCkd7bAmTGrgEkyWM6XEq1P7qIC_Ne_pLNAV6DLXUpg9bUWEHhHPXIDYKHS-c3N9fPDt8UVvGI8n0rPMieTN92NsYZ_6OqLNpcm6TrhMNZ9eg5EC0IPySrrv62jE", "refresh_token": "BbwRuDnVfm7tRQk7qSYByFbQKK+shYPDinYA9+q5c/ovIE1xETyWitvq6PU8AHnI5FWb06Nl2BVoBwCHCUmFaeRXQQgYY/i5vIDEQ/TJYFLVPRHDc7CKILF0kMakWKDk7wJdl5J6k5mN38th4pAAZOubiRoZ+2npLC7OSZd5Mq8LCBayzqtyy/QA5MY9ywCgb1PErzrGQhzB3mNhKj7U51ZnYT3nS5nCH7iJkCjaKvd/Hwsx2M6pXnpY45xlDVeTOjZxxaOF/e0+VT2FP2+TZMDRfrSMLBEkpbyX0M/VxunriRJPXTUvl3PW0sVOEa3J7+fbce0XWAKz7PNs3+hcdzD2Av2VHYF7/bJwcDCO77ky0G4JlHjqC0HnnGP2UWI5qR+tCSBga7+M1P3ESjcTCV6G6H+7f8SOSv9FECcJ8J5WUrU+EHrZ95bDtPc9scE4P3OEQaYchlC9GHk2ZoGo5oMJI6YACuRfbGQJNBjdjxvLIrAMrB6DNGDMbH6UZodkpZgQjGVuoCWgFEfLqegHbp34CjwL5ZFJGohV+E87KxedXE6aEseywyjmGLGZwAekjsjNwuxqD2QMb05sg9VkiUPMsvn45K9iCLS5clEKOTwkd+JuWw2IU80pA24aXN64RvOJX5VKMN6CPluJVLdjHeFL55SB7nlDjp15WhoMU1A=" }
现在,您可以使用 laravel 护照提供的标准 POST API 通过使用以下参数的“oauth/token”密码授权请求访问令牌:
grant_type : 'password' client_id : '<email with which the user is registered>' client_secret : '<generate the client secret from the mobile app>' username : '<email with which the user is registered>' password : '<password entered by the user>' scope : '<leave empty as default>'
以上会给你一个回应,如果一切正确,类似于:
{ "token_type": "Bearer", "expires_in": 3155673600, "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjMwZmM0MDk1NWY5YjUwNDViOTUzNDlmZjc2M2ExNDUxOTAxZjc5YTA5YjE4OWM1MjEzOTJlZmNiMDgwOWQzMzQwM2ExZWI4ZmMyODQ1MTE3In0.eyJhdWQiOiJzaHVqYWhtQGdtYWlsLmNvbSIsImp0aSI6IjMwZmM0MDk1NWY5YjUwNDViOTUzNDlmZjc2M2ExNDUxOTAxZjc5YTA5YjE4OWM1MjEzOTJlZmNiMDgwOWQzMzQwM2ExZWI4ZmMyODQ1MTE3IiwiaWF0IjoxNDc4MTQ1NjMyLCJuYmYiOjE0NzgxNDU2MzIsImV4cCI6NDYzMzgxOTIzMiwic3ViIjoiMSIsInNjb3BlcyI6W119.dj3g9b2AdPCK-im5uab-01SP71S7AR96R0FQTKKoaZV7M5ID1pSXDlmZw96o5Bd_Xsy0nUqFsPNRQsLvYaOuHZsP8v9mOVirBXLIBvPcBc6lDRdNXvRidNqeh4JHhJu9a5VzNlJPm3joBYSco4wYzNHs2BPSxXuuD3o63nKRHhuUHB-HwjVxj2GDwzEYXdZmf2ZXOGRJ99DlWGDvWx8xQgMQtd1E9Xk_Rs6Iu8tycjBpKBaC24AKxMI6T8DpelnFmUbMcz-pRsgCWCF_hxv6FpXav3jr1CLhhT58_udBvXjQAXEbtHeB7W_oaMcaqezHdAeOWDcnqREZHsnXHtKt0JpymcTWBkS2cg7sJzy6P9mOGgQ8B4gb8wt44_kHTeWnokk4yPFRZojkHLVZb8YL6hZxLlzgV1jCHUxXoHNe1VKlHArdlV8LAts9pqARZkyBRfwQ8oiTL-2m16FQ_qGg-9vI0Suv7d6_W126afI3LxqDBi8AyqpQzZX1FWmuJLV0QiNM0nzTyokzz7w1ilJP2PxIeUzMRlVaJyA395zq2HjbFEenCkd7bAmTGrgEkyWM6XEq1P7qIC_Ne_pLNAV6DLXUpg9bUWEHhHPXIDYKHS-c3N9fPDt8UVvGI8n0rPMieTN92NsYZ_6OqLNpcm6TrhMNZ9eg5EC0IPySrrv62jE", "refresh_token": "BbwRuDnVfm7tRQk7qSYByFbQKK+shYPDinYA9+q5c/ovIE1xETyWitvq6PU8AHnI5FWb06Nl2BVoBwCHCUmFaeRXQQgYY/i5vIDEQ/TJYFLVPRHDc7CKILF0kMakWKDk7wJdl5J6k5mN38th4pAAZOubiRoZ+2npLC7OSZd5Mq8LCBayzqtyy/QA5MY9ywCgb1PErzrGQhzB3mNhKj7U51ZnYT3nS5nCH7iJkCjaKvd/Hwsx2M6pXnpY45xlDVeTOjZxxaOF/e0+VT2FP2+TZMDRfrSMLBEkpbyX0M/VxunriRJPXTUvl3PW0sVOEa3J7+fbce0XWAKz7PNs3+hcdzD2Av2VHYF7/bJwcDCO77ky0G4JlHjqC0HnnGP2UWI5qR+tCSBga7+M1P3ESjcTCV6G6H+7f8SOSv9FECcJ8J5WUrU+EHrZ95bDtPc9scE4P3OEQaYchlC9GHk2ZoGo5oMJI6YACuRfbGQJNBjdjxvLIrAMrB6DNGDMbH6UZodkpZgQjGVuoCWgFEfLqegHbp34CjwL5ZFJGohV+E87KxedXE6aEseywyjmGLGZwAekjsjNwuxqD2QMb05sg9VkiUPMsvn45K9iCLS5clEKOTwkd+JuWw2IU80pA24aXN64RvOJX5VKMN6CPluJVLdjHeFL55SB7nlDjp15WhoMU1A=" }
Its only a temporary solution till laravel supports an external API for applications which only has a mobile as the only possible interface for creating oAuth clients and user.
它只是一个临时解决方案,直到 laravel 支持应用程序的外部 API,该应用程序只有移动设备作为创建 oAuth 客户端和用户的唯一可能接口。
Hope it helps you! Cheers.
希望对你有帮助!干杯。
回答by Andre F.
Because the marked answer was noted as correct I feel it necessary to note some key points that many I think would agree with:
因为标记的答案被认为是正确的,所以我觉得有必要注意一些我认为许多人会同意的关键点:
You almost NEVERwant put server process logic of that kind within your routes directory. Especially when working to create an API with the intent to put it into production. It's a dirty route to take and not entirely safe. UNLESSit's for things that are safe to process within your routes directory. Like, on a lesser scale, the base logic for sending a notification (SMS,email,push,slack) to staff members about a new letter/blog/memo being published as an example.
ALWAYSattempt to leverage and make use of as much of a framework's features as possible before attempting to "hackishly" accomplish a task that may have been accomplished multiple times before.
Ensure that you're doing the proper research about something that has been accomplished already. That way it makes it easier to simply reference a video or tutorial that shows how to properly do what someone is trying to do.
你几乎从不想把那种服务器进程逻辑放在你的路由目录中。特别是在努力创建 API 以将其投入生产时。这是一条肮脏的路线,并不完全安全。 除非它是为了在你的路由目录中安全处理的事情。例如,在较小的范围内,向工作人员发送关于新信件/博客/备忘录的通知(短信、电子邮件、推送、松弛)的基本逻辑作为示例。
在尝试“hackishly”完成之前可能已多次完成的任务之前,始终尝试尽可能多地利用和使用框架的功能。
确保您正在对已经完成的事情进行适当的研究。这样就可以更轻松地简单地参考视频或教程,该视频或教程展示了如何正确地做某人正在尝试做的事情。
That being said, a good starting point would be to watch the following video that perfectly describes the basics of how to properly set up what you're looking to set up:
话虽如此,一个很好的起点是观看以下视频,该视频完美地描述了如何正确设置您要设置的内容的基础知识:
https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/13
https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/13
In many respects, the video tutorial is very well done and thorough from start to finish. Be sure to brush up on the different Grant_Types for OAuth2.0 as well so you'll have a better understanding as to what specific type you/your application need based on your application's position to consume the api:
在许多方面,视频教程从头到尾都做得非常好和彻底。请务必复习 OAuth2.0 的不同 Grant_Types,以便您根据您的应用程序使用 api 的位置更好地了解您/您的应用程序需要什么特定类型:
https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2
https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2
In addition, be sure to USE laravel's out-of-the-box features for login and register when creating or logging in users. The Controllers are built for you when you perform the following in your console:
另外,在创建或登录用户时一定要使用laravel的开箱即用功能进行登录和注册。当您在控制台中执行以下操作时,控制器是为您构建的:
php artisan make:auth
Aside from that, if passport is some-what of a mystery, you can always pull in laravel/socialite package (https://github.com/laravel/socialite). It will allow you to "Log in with (Social Network Here)". Providedthat is the route you're also aiming to go.
除此之外,如果护照有点神秘,你总是可以拉入 laravel/socialite 包(https://github.com/laravel/socialite)。它将允许您“使用(此处的社交网络)登录”。前提是你也打算走这条路。
END NOTE:The piece I saw in your question that stuck out the most was how a person will register but will not login with facebook. Instead will have an access token to hit various API endpoints. So if I'm getting what you're saying right, you're aiming to use a user's data from facebook when data is returned, the user is considered logged in and is to be issued an access token. SO:
结束注意:我在你的问题中看到的最突出的是一个人如何注册但不会登录 Facebook。相反,将有一个访问令牌来访问各种 API 端点。因此,如果我理解您的意思,那么您的目标是在返回数据时使用来自 facebook 的用户数据,该用户被视为已登录并会获得访问令牌。所以:
Use socialite to send a "login with facebook" request to facebook. This will get the user's data and leverage a bit of facebook's process of authentication.
When a request is returned with user data within the body run it through a check to ensure that there is data (a simply if statement should be fine). Since facebook will have already authenticated that user and the sent credentials you shouldbe good to go.
You can either fire off an internal proxy within your Login Controller (which is the cleaner and safer way to do it) or you can issue a JWT (Which is covered in the last 5 minutes of the video posted in this answer above).
Below is some example code to get you started.
App\Http\Controllers\Auth\LoginController.php
class LoginController extends Controller { // ... protected function authenticateClient(Request $request) { $credentials = $this->credentials($request); $data = $request->all(); $user = User::where('email', $credentials['email'])->first(); $request->request->add([ 'grant_type' => $data['grant_type'], 'client_id' => $data['client_id'], 'client_secret' => $data['client_secret'], 'username' => $credentials['email'], 'password' => $credentials['password'], 'scope' => null, ]); $proxy = Request::create( 'oauth/token', 'POST' ); return Route::dispatch($proxy); } protected function authenticated(Request $request, $user) { return $this->authenticateClient($request); } protected function sendLoginResponse(Request $request) { $request->session()->regenerate(); $this->clearLoginAttempts($request); return $this->authenticated($request, $this->guard()->user()); } public function login(Request $request) { if ($this->guard('api')->attempt($credentials, $request->has('remember'))) { return $this->sendLoginResponse($request); } } }
使用社交名流向 facebook 发送“使用 facebook 登录”的请求。这将获取用户的数据并利用一些 facebook 的身份验证过程。
当请求在正文中返回用户数据时,通过检查运行它以确保有数据(简单的 if 语句应该没问题)。由于 facebook 已经对该用户和发送的凭据进行了身份验证,因此您应该很高兴。
您可以在登录控制器中触发内部代理(这是一种更干净、更安全的方法),也可以发出 JWT(在上面这个答案中发布的视频的最后 5 分钟中进行了介绍)。
下面是一些示例代码,可帮助您入门。
App\Http\Controllers\Auth\LoginController.php
class LoginController extends Controller { // ... protected function authenticateClient(Request $request) { $credentials = $this->credentials($request); $data = $request->all(); $user = User::where('email', $credentials['email'])->first(); $request->request->add([ 'grant_type' => $data['grant_type'], 'client_id' => $data['client_id'], 'client_secret' => $data['client_secret'], 'username' => $credentials['email'], 'password' => $credentials['password'], 'scope' => null, ]); $proxy = Request::create( 'oauth/token', 'POST' ); return Route::dispatch($proxy); } protected function authenticated(Request $request, $user) { return $this->authenticateClient($request); } protected function sendLoginResponse(Request $request) { $request->session()->regenerate(); $this->clearLoginAttempts($request); return $this->authenticated($request, $this->guard()->user()); } public function login(Request $request) { if ($this->guard('api')->attempt($credentials, $request->has('remember'))) { return $this->sendLoginResponse($request); } } }
The code above is used IN CASEyou're aiming to use the Password Granttype for authenticating clients through passport. However, I would seriously look at the tutorial video before jumping the gun on anything. It WILL help you out a lot with how to use laravel 5.3 with passport.
上面的代码被用于万一您的目标是使用密码格兰特类型通过护照认证的客户端。但是,我会认真查看教程视频,然后再对任何事情采取行动。它将为您提供如何使用带有护照的 laravel 5.3 的很多帮助。