简体   繁体   English

在 laravel 护照客户端应用程序中使用访问令牌获取用户数据

[英]Get user data using access token in laravel passport client app

I have successfully created server.app and client.app using Laravel Passport documentation .我已经使用Laravel Passport 文档成功创建了server.appclient.app Everything works as expected.一切都按预期工作。

client.app Route: client.app 路由:

Route::get('callback', function (Request $request) {
   $http = new GuzzleHttp\Client;
   $response = $http->post('http://server.app/oauth/token', [
    'form_params' => [
        'grant_type' => 'authorization_code',
        'client_id' => 3,
        'client_secret' => 'secret',
        'redirect_uri' => 'http://client.app/callback',
        'code' => $request->code
    ]
   ]);
   return json_decode((string) $response->getBody(), true)['access_token'];
});

By default, this route returns access_token , with which i can do whatever i want.默认情况下,这条路线返回access_token ,我可以用它做任何我想做的事。

Request:要求:

http://server.app/oauth/authorize?client_id=3&redirect_uri=http%3A%2F%2Fclient.app%2Fcallback&response_type=code&scope=

Returns:返回:

http://client.app/callback?code=access_token

Question:题:

How to make correct request to server.app with given access_token in client.app to get for example user(s) email(s) .如何使用client.app 中给定的 access_token 向server.app发出正确请求以获取例如用户电子邮件

Should i use: http://server.app/api/user request to get data?我应该使用: http://server.app/api/user : http://server.app/api/user请求来获取数据吗? If yes, how i can do that?如果是,我该怎么做? If possible, please write a code.如果可能,请写一个代码。

Thanks for any answers.感谢您提供任何答案。

I've been going absolutely insane about this issue! 我一直对这个问题感到十分疯狂! It just made no freaking sense as to why it kept spitting out the stupid Unauthenticated error when trying to hit-up a route such as /api/user . 它只是毫不掩饰地意识到为什么它在尝试启动/api/user这样的路由时不断吐出愚蠢的Unauthenticated错误。 After much searching (MUCH searching), I finally found the answer. 经过多次搜索(多次搜索),我终于找到了答案。 If you see this fero from Laracasts, you're my hero! 如果你从Laracasts看到这个fero,你就是我的英雄!

Did you check app\\Providers\\RouteServiceProvider.php ? 你检查了app\\Providers\\RouteServiceProvider.php吗?

in the mapApiRoutes() you can set the middleware . mapApiRoutes()你可以设置中间件 check to make sure its auth:api . 检查以确保其auth:api if its not, change it. 如果没有,改变它。 also, remove the auth middleware from the route api.php file. 另外,从路由api.php文件中删除auth 中间件

https://laracasts.com/discuss/channels/laravel/laravel-53-passport-api-unauthenticated-in-postman-using-personal-access-tokens https://laracasts.com/discuss/channels/laravel/laravel-53-passport-api-unauthenticated-in-postman-using-personal-access-tokens

Edit: 编辑:

Once you've made the change to the app\\Providers\\RouteServiceProvider.php mentioned above, proceed with the below example. 对上面提到的app\\Providers\\RouteServiceProvider.php进行更改后,请继续下面的示例。

First things first, we need to retrieve a fresh access_token . 首先,我们需要检索一个新的access_token To do this, I'm using the password grant_type (more info: https://laravel.com/docs/5.4/passport#password-grant-tokens ) 为此,我使用密码 grant_type (更多信息: httpsgrant_type

To retrieve a fresh access_token , I've created a new route on routes/web.php and called it /connect . 为了检索一个新的access_token ,我在routes/web.php上创建了一个新路由并将其称为/connect I've then placed the code from the above link into it: 然后我将上面链接中的代码放入其中:

Route::get('connect', function (Request $request) {
    $http = new GuzzleHttp\Client;

    $response = $http->post('http://example.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'password',
            'client_id' => $request->client_id,
            'client_secret' => $request->client_secret,
            'username' => $request->username,
            'password' => $request->password,
            'scope' => ''
        ],
    ]);

    return json_decode((string) $response->getBody(), true);
});

Using Chrome Postman , you need to: 使用Chrome Postman ,您需要:

  1. Set the method to GET 将方法设置为GET
  2. Enter the connect URL with the relevant params ie http://example.com/connect?client_id=1&client_secret=W2zogh7tiBh2jfHleYuzpViv7dqynDYQ6O07DKLj&username=test@test.com&password=123456 输入带有相关参数的连接URL,即http://example.com/connect?client_id=1&client_secret=W2zogh7tiBh2jfHleYuzpViv7dqynDYQ6O07DKLj&username=test@test.com&password=123456
  3. Click the headers tab (it's next to Authorization), add a key of Accept and value of application/json 单击headers选项卡(它位于Authorization旁边),添加Accept键和application/json
  4. Hit the Send button 点击发送按钮

Example result: 示例结果:

{
  "token_type": "Bearer",
  "expires_in": 31535999,
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6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MVD2DzA3JKDKvZTp5x92kP821",
  "refresh_token": "ArOWW0glHjflLpL4fKOsrNUXT5v91u+CjwcE8LBvH7GJsaM0gWaFe8GH9zXjh8SHew+cg7v1IMiIPLYSVdf7h8oOeV7wgwjChI9YM0Kt6iE4wOXJuy0VwPSCj+danHDuWC3nJWYLrPydTE3h/jgFNjWEPfgXGLfiRWjWQMozddz5EWd4pvUI7J64Lw6cMCg/BslZLHtfN7IWoC1RQGp5K0cGO0QmZfsGMSzsoSUNFjv16BXiKSqlNvs5aGhxErFY4wEOKqBifXUkb3SwnK/iHKg3irmqj4fOf/aKNyCdd/PJCHrRPocrW83oM1sjq7eDufEIlgxmy7uRset8GLAWjx/n6rzkxz2QM0/9Lyc/XN9OL00XBYjA47a1wL55qUUUYWevaFwxWX8LG2UjBf9Vv2lfvLcBBkbgqpalePMDh6wb8IDyJek4BbvZtJ1VZ/l+A9XXY9rQt/hIDdoOAtib8CGr9/CERFIrByZa3TEJBCLAa2FvJSIhHVnKvnuvZX3e9qhTkgHqowJrWg2C3VyPDQYAdIhdpTEvs0pcGSAZWhwXfu9xKQOeyRTEScbLKQmuW+sGbwU+qfdLgh/BR5kW4TMer4TIzWKSuHsqmibgiUwaQkwTrtjH2Xz9Z9XmAbVzJ8pqbEZPe7t5whXDoRSnAwWymdxk2E7SiSsVUA3kX39="
}

Highlight the access_token string and copy it to a text editor. 突出显示access_token字符串并将其复制到文本编辑器。

You'll then need to create a new route in routes/api.php . 然后,您需要在routes/api.php创建一个新路由。 The route below will simply output the current API users' info: 以下路线将只输出当前API用户的信息:

Route::group(['prefix' => 'user'], function() {
    Route::get('/', function() {
        return response()->json(request()->user());
    });
});

Once you've done the above, make these changes to Postman: 完成上述操作后,对Postman进行以下更改:

  1. Set the method to GET 将方法设置为GET
  2. Change the URL to point to the API route ie http://example.com/api/user 更改URL以指向API路由,即http://example.com/api/user
  3. Click on the headers tab again and add a new key of Authorization and value of Bearer access_token_here (replace access_token_here with the access token you copied earlier) 再次单击标题选项卡并添加新的Authorization密钥和Bearer access_token_here值(将access_token_here替换为您之前复制的访问令牌)
  4. Hit the Send button 点击发送按钮

Example output: 示例输出:

{
  "id": "75ced500-1544-11e7-9a8e-ad5f1aee389e",
  "name": "test test",
  "email": "test@test.com",
  "created_at": "2017-03-30 23:29:03",
  "updated_at": "2017-03-30 23:29:03"
}

Have you tried running it on POSTMAN chrome app? 你试过在POSTMAN chrome app上运行吗? If not, download it. 如果没有,请下载它。 https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en

Fill the information. 填写信息。 在此输入图像描述

After you successfully generated the data, click the CODE button from the top-right (I highlighted it with green). 成功生成数据后,单击右上角的CODE按钮(我用绿色突出显示它)。

Lastly, select your language and copy the code. 最后,选择您的语言并复制代码。 For PHP, I selected php cURL. 对于PHP,我选择了php cURL。

Hope it works. 希望它有效。

According to Laravel documentation , you should add route to server app ( routes/api.php ): $response->getBody(); 根据Laravel 文档 ,您应该添加到服务器应用程序的routes/api.phproutes/api.php ): $response->getBody();

Route::get('/user', function () {
    // authenticated user. Use User::find() to get the user from db by id
    return app()->request()->user();
})->middleware('auth:api');

Make request via quzzle: 通过quzzle提出请求:

$response = $client->request('GET', '/api/user', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$accessToken,
    ],
]);
echo $response->getBody();

I had the same problem and I tried all mentioned solutions but it remains same.我遇到了同样的问题,我尝试了所有提到的解决方案,但它仍然相同。 Read so many tutorial and websites but didn't get the solution.阅读了很多教程和网站,但没有得到解决方案。 Finally, got the solution : I am using laravel 8 and it has declared two packages for api request one is passport and other is sanctum.最后,得到了解决方案:我正在使用 laravel 8,它为 api 请求声明了两个包,一个是护照,另一个是圣所。 By default in User model it uses use Laravel\\Sanctum\\HasApiTokens;默认情况下,在User模型中它使用use Laravel\\Sanctum\\HasApiTokens; for api token.对于 api 令牌。 If you use Sanctum package it's ok.如果你使用Sanctum包就可以了。 If you don't use it (If you are using passport) then change the line from Sanctum to Passport as use Laravel\\Passport\\HasApiTokens;如果您不使用它(如果您使用的是护照),则将行从 Sanctum 更改为 Passport 为use Laravel\\Passport\\HasApiTokens;

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM